JAVA中Exception丢失现象
第一种情况:
public class LostException { public void f() throws VeryImportantException{ throw new VeryImportantException(); } public void d() throws LittleException{ throw new LittleException(); } public static void main(String[] args) { try{ LostException l = new LostException(); try{ l.f(); }finally{ l.d(); } }catch(Exception e){ e.printStackTrace(); } } } class VeryImportantException extends Exception{ public String toString(){ return "a very important excetion"; } } class LittleException extends Exception{ public String toString(){ return "a little exception"; } }
结果:丢失了try中的异常
第二种情况:
public class LostException2 { public static void main(String[] args) { try{ throw new RuntimeException(); }finally{ return; } } }
结果:丢失了try中的异常;
第三种情况:
public class LostException3 { public static void main(String[] args) { try{ try{ throw new RuntimeException("a"); }catch(Exception e1){ try{ String s = null; s.split(","); }finally{ throw new Exception(); //return; } //throw e1; } }catch(Exception e){ e.printStackTrace(); } System.out.println("OK"); } }
结果:丢失了内层和外层try中的异常;
第四种情况:
public class LostException4 { private static Logger logger = LoggerFactory.getLogger(LostException4.class); public static void main(String[] args) { String s = null; int i = 0; while(true){ try{ int[] a = null; a[2] = 1; }catch(Exception e){ i++; s =ExceptionUtils.getFullStackTrace(e); logger.error("msg:",e); if(e.getStackTrace().length==0){ break; } } } System.out.println(i); System.out.println(s); } }
结果:jdk5以上优化,打印了一定次数的异常信息后,堆栈信息会被省略。也就是说这个程序最后会break;