Java学习——关于异常

异常体系结构



Java异常处理机制
异常处理五个关键字
-
try , catch , finally , throw , throws
抛出异常
1 public void test(int a,int b){ 2 if (b == 0) { //throw 主动抛出异常,一般在方法中使用 3 throw new ArithmeticException(); 4 } 5 System.out.println(a / b); 6 } 7 //假设在方法中处理不了异常,可以在方法上抛出异常 8 public void test(int a,int b) throws ArithmeticException{ 9 if (b == 0) { 10 throw new ArithmeticException(); 11 } 12 System.out.println(a / b); 13 }
捕获异常
catch(想要捕获的异常类型),可以同时有多个catch,但类型不能相同,且范围要从小到大。
1 //快捷键:选中按ctrl + alt + t 2 public class Test { 3 4 public static void main(String[] args) { 5 6 int a = 1; 7 int b = 0; 8 9 try {//try监控区域 10 System.out.println(a/b); 11 }catch (ArithmeticException e){//catch(想要捕获的异常类型),捕获异常 12 System.out.println("程序出现异常,变量b不能为零"); 13 }finally {//finally处理善后工作 14 System.out.println("finally"); 15 } 16 17 //finally 可以不要 18 19 } 20 21 public void a(){ 22 b(); 23 } 24 public void b(){ 25 a(); 26 } 27 28 }

自定义异常

1 //自定义的异常类 2 public class MyException extends Exception { 3 4 //传递数字>10 5 private int detail; 6 7 public MyException(int a) { 8 this.detail = a; 9 } 10 11 //toString:异常的打印信息 12 13 @Override 14 public String toString() { 15 return "MyException{" + 16 "detail=" + detail + 17 '}'; 18 } 19 }
1 public class Test { 2 3 //可能会存在异常的方法 4 static void test(int a) throws MyException { 5 6 System.out.println("传递的参数为:"+a); 7 if(a>10) { 8 throw new MyException(a);//抛出 9 } 10 System.out.println("ok"); 11 } 12 13 public static void main(String[] args) { 14 try { 15 test(111); 16 } catch (MyException e) { 17 System.out.println("MyException=>"+e); 18 } 19 }
总结



浙公网安备 33010602011771号