這幾天工做遇到Exception的問題。java
1:出現異常剩下代碼如何運行?代碼以下:web
public class ExceptionTest { public static void main(String[] args) { ExceptionTest foo = new ExceptionTest(); foo.dateFormat(null); System.out.println("step end"); } public Date dateFormat(String str){ Date d = new Date(); try { d = new SimpleDateFormat("yyyy-MM-dd").parse(str); } catch (ParseException e) { //} catch (Exception e) { e.printStackTrace(); System.out.println("exception..."); } System.out.println("method end"); return d; } }
本來個人理解出現的打印順序應該是: 打印「堆棧異常信息」->「exception...」->「method end」->"step end"spa
可是實際結果以下,異常1: code
Exception in thread "main" java.lang.NullPointerException at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1380) at java.text.DateFormat.parse(DateFormat.java:355) at webtest.ExceptionTest.dateFormat(ExceptionTest.java:19) at webtest.ExceptionTest.main(ExceptionTest.java:11)
因而我把捕獲異常範圍擴到最大,也就是catch(Exception e),打印結果以下,異常2: orm
java.lang.NullPointerException at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1380) at java.text.DateFormat.parse(DateFormat.java:355) at webtest.ExceptionTest.dateFormat(ExceptionTest.java:17) at webtest.ExceptionTest.main(ExceptionTest.java:10) exception... method end step end
因而這個結果算是符合個人預期。可是我仍是有點不明白「異常1"若是說傳入null不屬於ParseException異常的話,疑問:io
(1)那這個異常被誰捕獲了?
class
(2)個人理解打印順序應該是:"堆棧異常信息"->"method end"->"step end",那又是誰中斷了程序運行呢?thread
2,異常被拋出,調用方法如何處理?代碼以下:test
public class ExceptionTest { public static void main(String[] args) { ExceptionTest foo = new ExceptionTest(); try { foo.dateFormat(null); } catch (Exception e) { e.printStackTrace();//堆棧異常信息2 System.out.println("main method exception"); } System.out.println("step end"); } public Date dateFormat(String str) throws Exception{ Date d = new Date(); try { d = new SimpleDateFormat("yyyy-MM-dd").parse(str); //} catch (ParseException e) { } catch (Exception e) { e.printStackTrace();//堆棧異常信息1 System.out.println("exception..."); } System.out.println("method end"); return d; } }
我本來預期打印結果:"堆棧異常信息1"->"exception..."->"method end"->我也不知道"堆棧異常信息2"會不會出現->""->"main method exception"->"step end".date
實際打印結果:
java.lang.NullPointerException at java.text.SimpleDateFormat.parse(SimpleDateFormat.java:1380) at java.text.DateFormat.parse(DateFormat.java:355) at webtest.ExceptionTest.dateFormat(ExceptionTest.java:22) at webtest.ExceptionTest.main(ExceptionTest.java:11) exception... method end step end
疑問:
(1)main方法爲何沒有捕獲異常?