1.
public static void main(String[] a) { int i=1, j=0, k; k=i/j; try { k = i/j; // Causes division-by-zero exception //throw new Exception("Hello.Exception!"); } catch ( ArithmeticException e) { System.out.println("被0除. "+ e.getMessage()); } catch (Exception e) { if (e instanceof ArithmeticException) System.out.println("被0除"); else { System.out.println(e.getMessage()); } } finally { JOptionPane.showConfirmDialog(null,"OK"); }
程序报如下错误:
当我们将try外面的i/j注释掉运行结果变成如下:
再将try里面的i/j注释掉,将throw new Exception("Hello.Exception!");的注释解除得到:
我们可以得到java对于异常处理的一些基础知识:
1.java通过try...catch实现对于异常的处理,如果没有try..catchjava虚拟机将退出。
2.不管异常是否出现finally的语句一定会被执行。
3.当有多个catch时java会从上到下匹配,找到后执行catch中的语句,且之后的catch不会被执行。
2.
duoble类型的运行结果:
其实由此可以看出浮点型与整型的计算原理是不一样的。
浮点型中引入了无限的概念:
System.out.println((1.0 / 0)); // Infinity
System.out.println((-1.0 / 0)); // -Infinity
System.out.println((1.0 / 0.0) * 0);// NAN
System.out.println(0.0d / 0.0); // NAN
System.out.println((1.0 / 0) == (1.0 / 0));// true
所以输出了Infinity而不会报错。
3.
下面为运行结果:
内层的try抛出了Array...这个错误,在内层的catch中匹配到,所以输出了内层的语句而不会输出外层的。
外层的try抛出了Arithmetic..这个错误外层第一个catch匹配,所以得到了以上结果。
以下为运行结果:
内层的try抛出了Array...的异常但是内层的没有与之配对的catch,所以它向外层寻找,并最终执行了外层的Array的catch。
而且我们发现外层try的ArithmenticException并没有抛出。
综上两个实例我们可以总结出java多层异常捕获的规律:
1.内层try的异常不仅仅会在内层寻找与之配对的catch,也会在外层寻找。
2.内层抛出了异常如果与之匹配的catch实在外层的则外层的异常并不会抛出。
4.
以下为代码:
int result; try { System.out.println("in Level 1"); try { System.out.println("in Level 2"); // result=100/0; //Level 2 try { System.out.println("in Level 3"); result=100/0; //Level 3 } catch (Exception e) { System.out.println("Level 3:" + e.getClass().toString()); } finally { System.out.println("In Level 3 finally"); } // result=100/0; //Level 2 } catch (Exception e) { System.out.println("Level 2:" + e.getClass().toString()); } finally { System.out.println("In Level 2 finally"); } // result = 100 / 0; //level 1 } catch (Exception e) { System.out.println("Level 1:" + e.getClass().toString()); } finally { . System.out.println("In Level 1 finally"); }
以下为运行结果:
看起来并不难理解,第三层出错,第三层的catch捕获而且finally被执行,单要注意1,2层的finally也执行了。
我们将三层加上注释,把二层的注释(第三层try之前)去掉观察运行结果:
我们发现二层的catch捕获了异常,1,2层的finally执行,而第三层的没有执行。
我们将第二层中第三层try之后的注释去掉观察运行结果:
我们发现1,2,3层的finally都执行了但是第三层的finally在第二层抛出错误之前。
那我们不难猜测出第一层try去掉注释后的结果:
我们可以总结得到:
嵌套的finally是否执行取决于出错的位置:若最内层出错,则毫无疑问所有的finally都会执行。
若在外层出错:由于语句会从上到下执行,若外层出错位置在内层finally之后则会执行内层的finally否则不会执行(不管内层有没有错误)。
5.
以下为代码:
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"); }
以下为运行结果:
由于catch中有exit(0)所以finally不执行。
但是有一个有趣的现象,将//System.exit(0);的注释去掉,会报错,担当把它移到throw new Exception之前就不会报错了。