分享一段測試try catch 執行順序和那些代碼後續執行,那麼不執行的代碼:
@Test
public void testTryCatch(){
try {
System.out.println(" 外層 try !" );
//Integer.parseInt(null);
try {
System.out.println(" 外層 try的 內層 try " );
Integer.parseInt(null);
}
catch (Exception ex2) {
Integer.parseInt(null);
System.out.println(" 外層 try的 內層 catch " );
}
finally {
Integer.parseInt(null);
System.out.println(" 外層 try的 內層 finally");
}
System.out.println("外層 try 異常之後執行!");
Integer.parseInt(null);
}
catch (Exception ex) {
try {
System.out.println(" 內層 try " );
Integer.parseInt(null);
}
catch (Exception ex2) {
System.out.println(" 內層 catch " );
}
finally {
System.out.println(" 內層 finally");
}
System.out.println("外層 catch " );
}
finally {
System.out.println("外層 finally!");
}
}
通過註釋 Integer.parseInt(null); 完成自己想要跑異常的點,完後看後續處理的順序。
總結:拋出異常的點,後續代碼不執行,然後找最近的catch,執行catch和finally,然後再往外層執行。
但是如果catch內部再次出現異常,會往外層拋,直到找到最近的catch。所以在使用嵌套trycatch的時候需要注意的地方就是,哪裏會拋出異常,異常的順序,那些後續可能不會執行。
再分享一段spring的代碼
if (this.registrar.hasTasks() && this.registrar.getScheduler() == null) {
Assert.state(this.beanFactory != null, "BeanFactory must be set to find scheduler by type");
try {
// Search for TaskScheduler bean...
this.registrar.setTaskScheduler(this.beanFactory.getBean(TaskScheduler.class));
}
catch (NoSuchBeanDefinitionException ex) {
logger.debug("Could not find default TaskScheduler bean", ex);
// Search for ScheduledExecutorService bean next...
try {
this.registrar.setScheduler(this.beanFactory.getBean(ScheduledExecutorService.class));
}
catch (NoSuchBeanDefinitionException ex2) {
logger.debug("Could not find default ScheduledExecutorService bean", ex);
// Giving up -> falling back to default scheduler within the registrar...
}
}
}
最後說一下個人的觀點,儘量避免使用嵌套異常處理工作。除非邏輯簡單,有一定的可讀性,不然會極大的影響可讀性,另外就是避免一些後續處理邏輯異常。