//代码1 public static void test() throws Exception { throw new Exception("参数越界"); System.out.println("异常后"); //编译错误,「无法访问的语句」 }
//代码2 try{ throw new Exception("参数越界"); }catch(Exception e) { e.printStackTrace(); } System.out.println("异常后");//可以执行
//代码3 if(true) { throw new Exception("参数越界"); } System.out.println("异常后"); //抛出异常,不会执行
总结 :
另外总结一下运行时异常与非运行时异常的区别:
public static void test() throws Exception { throw new Exception("参数越界"); System.out.println("异常后"); //编译错误,「无法访问的语句」 }
//代码2 //异常被捕获,日志打印了异常,代码继续执行 try{ throw new Exception("参数越界"); }catch(Exception e) { e.printStackTrace(); } System.out.println("异常后");//可以执行
//psvm 快捷键 public static void main(String[] args) { try { test(); } catch (Exception e) { e.printStackTrace(); } } public static void test() throws Exception { //代码3 if(true) { throw new Exception("参数越界"); } System.out.println("异常后"); //抛出异常,不会执行 }
public static void test() throws Exception { //代码4 try { int i=1/0; } catch (Exception e) { e.printStackTrace(); throw new Exception("代码执行异常后打印并抛出异常提示"); } System.out.println("异常后"); //抛出异常,不会执行 } //打印日志 java.lang.ArithmeticException: / by zero at zmc.eter.etern.text.text.test(text.java:23) at zmc.eter.etern.text.text.main(text.java:14) java.lang.Exception: 代码执行异常后打印并抛出异常提示 at zmc.eter.etern.text.text.test(text.java:26) at zmc.eter.etern.text.text.main(text.java:14)
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。