课后整理总结-10.17
异常处理-动手动脑问题
1.
运行AboutException.java
出现:数学运算异常——java.lang.ArithmeticException
原因是除数为0了
2.
CatchWho.java
public class CatchWho { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); } throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("发生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); } } }
运行结果:
ArrayIndexOutOfBoundsException/内层try-catch
发生ArithmeticException
CatchWho2.java
public class CatchWho2 { public static void main(String[] args) { try { try { throw new ArrayIndexOutOfBoundsException(); } catch(ArithmeticException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch"); } throw new ArithmeticException(); } catch(ArithmeticException e) { System.out.println("发生ArithmeticException"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch"); } } }
程序运行的结果:
ArrayIndexOutOfBoundsException/外层try-catch
3.
EmbedFinally.java运行结果:
finally语句块一定会执行吗?SystemExitAndFinally.java
public class SystemExitAndFinally { public static void main(String[] args) { try{ System.out.println("in main"); throw new Exception("Exception is thrown in main"); //System.exit(0); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(0); } finally { System.out.println("in finally"); } } }
运行结果:
显然并不是一定执行。
存在很多特殊情况导致 finally 语句块不执行。如:
直接返回未执行到 try-finally 语句块
抛出异常未执行到 try-finally 语句块
系统退出未执行到 finally 语句块