当某个方法抛出异常时:java
import java.lang.String; public class Main { public static void main(String[] args) { try{ process1(); }catch (Exception e){ e.printStackTrace();//对于调试错误很是有用 } } static void process1(){ process2(); } static void process2() { Integer.parseInt(null); } }
import java.lang.String; public class Main { public static void main(String[] args) { try{ process1(""); }catch (Exception e){ e.printStackTrace(); } } static void process1(String s){ throw new IllegalArgumentException(); } }
若是一个方法捕获了某个异常后,又在catch子句中抛出新的异常,就至关与把抛出的异常类型“转换”了。3d
import java.lang.String; public class Main { public static void main(String[] args) { process1(""); } static void process1(String s){ try{ process2(s); }catch (NullPointerException e){ throw new IllegalArgumentException();//捕获NullPointerException,抛出IllegalArgumentException } } static void process2(String s){ throw new NullPointerException(); } }
上例中存在的问题:新的异常丢失了原始异常信息,只追踪到process1。如何让新的Exception能够持有原始异常信息?
解决方法:将异常传入便可。
throw new IllegalArgumentException(e);调试
import java.lang.String; public class Main { public static void main(String[] args) { process1(""); } static void process1(String s){ try{ process2(s); }catch (NullPointerException e){ throw new IllegalArgumentException(e); } } static void process2(String s){ throw new NullPointerException(); } }
在抛出异常前,finally语句会保证执行。
若是finally语句抛出异常,则catch语句再也不抛出,没有被抛出的异常被称为“被屏蔽”的异常(suppressed exception)code
import java.lang.String; public class Main { public static void main(String[] args) { try{ process1(""); }catch (Exception e){ System.out.println("catched"); throw new RuntimeException(e);//“被屏蔽”的异常(suppressed exception) }finally { System.out.println("finally"); //throw new NullPointerException(); } } static void process1(String s){ throw new IllegalArgumentException(); } }
finally中不抛出异常
finally中抛出异常
throw new NullPointerException();去掉注释
所以尽可能避免在finally中抛出异常blog
import java.lang.String; public class Main { public static void main(String[] args) throws Exception { Exception origin = null; try{ process1(""); }catch (Exception e){ origin = e; System.out.println("catch捕捉到了"); throw new RuntimeException("可能屏蔽的异常"+e); }finally { System.out.println("finally"); try{ throw new NullPointerException("finally 抛出的异常"); }catch (Exception e){ if (origin != null ){ origin.addSuppressed(e); }else{ origin = e; } } if (origin != null){ throw origin; } } } static void process1(String s){ throw new IllegalArgumentException("process1方法异常了,32"); } }
由于通常不在finally中捕获异常,因此能够直接使用for循环将异常信息打印出来。get
import java.lang.String; public class Main { public static void main(String[] args) throws Exception { Exception origin = null; try{ process1(""); }catch (Exception e){ e.printStackTrace(); for(Throwable t:e.getSuppressed()){ t.printStackTrace(); } }finally { System.out.println("finally"); } } static void process1(String s){ throw new IllegalArgumentException("process1方法异常了,32"); } }