这几天工做遇到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方法为何没有捕获异常?