一、异常处理机制
-
抛出异常
-
捕获异常
-
异常处理五个关键字
-
try、catch、finally、throws、throw
-
-
快捷键:ctrl + alt + t
public class Test { public static void main(String[] args) { int a =1; int b =0; try { new Test().test(a,b); } catch (ArithmeticException e) { e.printStackTrace(); } } public void a(){b();}; public void b(){a();}; //假设这个方法中,处理不了这个异常,方法上抛出异常 public void test(int a, int b ) throws ArithmeticException{ if(b==0){//主动的抛出异常 throw throws throw new ArithmeticException();//主动抛出异常,一般在方法中使用 } System.out.println(a/b); } /* //假设要捕获多个异常,从小到大!否则会报错 try{//try监控区域 if(b==0){//主动的抛出异常 throw throws throw new ArithmeticException();//主动抛出异常 } System.out.println(a/b); }catch (Error e){//catch(想要捕获的异常类型) catch捕获异常 System.out.println("Error"); }catch (Exception e){ System.out.println("Exception"); }catch (Throwable t){ System.out.println("Throwable"); } finally {//finally处理善后工作 System.out.println("finally"); } //finally 可以不要finally ,假设IO,资源,关闭! */ } public class Test02 { public static void main(String[] args) { int a =1; int b =0; //ctrl + alt + t try { System.out.println(a/b); } catch (Exception e) { System.exit(1);//手动把程序完结 e.printStackTrace();//打印错误的栈信息 } finally { } } }
二、自定义异常
-
使用Java内置的异常类可以描述在编程时出现的大部分异常情况。除此之外,用户还可以自定义异常。用户自定义异常类,只需继承Exception类即可。
-
在程序中使用自定义异常类,大体可分为以下几个步骤:
-
创建自定义异常类
-
在方法中通过throw关键字抛出异常对象
-
如果在当前抛出异常的方法中处理异常,可以使用try-catch语句捕获并处理;否则在方法的声明处通过throws关键字指明要抛出给方法调用者的异常,继续进行下一步操作。
-
在出现异常方法的调用者中捕获并处理异常。
-
public class Demo { //可能会存在异常的方法 static void test(int a) throws MyException { System.out.println("传递的参数为:"+a); if (a>10){ throw new MyException(a);//抛出 } System.out.println("ok"); } public static void main(String[] args) { try { test(11); } catch (MyException e) { System.out.println("MyException=>"+e); } } } //自定义的异常类 public class MyException extends Exception{ //传递数字>10 private int detail; public MyException(int detail) { this.detail = detail; } //toString 异常的打印信息 @Override public String toString() { return "MyException{" + "detail=" + detail + '}'; } }
三、实际应用中的经验总结
-
处理运行时异常时,采用逻辑去合理规避同时辅助try-catch处理
-
在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
-
对于不确定的代码,也可以加上try-catch,处理潜在的异常
-
尽量去处理异常,切忌只是简单地调用printStackTrace()去打印输出
-
具体如何处理异常,要根据不同的业务需求和异常类型去决定
-
尽量添加finally语句块去释放占用的资源