码迷,mamicode.com
首页 > 编程语言 > 详细

java异常处理动手动脑问题

时间:2017-11-16 21:57:21      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:多层嵌套   swing   结束   无效   option   oid   异常处理   ...   dex   

动手动脑01

源程序:

import javax.swing.*;
class AboutException {
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");
}
}
}

程序截图:

技术分享

 

动手动脑:多层的异常捕获-1

源程序:

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");
}
}
}

程序截图:

技术分享

 

动手动脑:多层的异常捕获-2

源程序:

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");
}
}
}

程序截图:

技术分享

动手动脑-----

当有多个嵌套的try...catch....finally时,要特别注意finally的执行时机

代码示例:

技术分享

执行结果:

技术分享

 

注意:

当有多层嵌套的finally时,异常在不同层次抛出,在不同的位置抛出,可能导致不同的finally语句执行顺序

动手动脑--------

辨析:finally语句一定会1执行吗?

示例代码:

技术分享

执行结果: 

技术分享

总结:
(1)try语句没有被执行到,如在try语句之前return就返回了,这样finally语句就不会执行。这也说明了finally语句被执行的必要而非充分条件是:相应的try语句一定被执行到。

(2)在try块|catch块中有System.exit(0);这样的语句。System.exit(0)是终止Java虚拟机JVM的,连JVM都停止了,所有都结束了,当然finally语句也不会被执行到。

在try-catch-finally中, 当return遇到finally,return对finally无效,即:

     1.在try catch块里return的时候,finally也会被执行。

     2.finally里的return语句会把try catch块里的return语句效果给覆盖掉。

结论:return语句并不一定都是函数的出口,执行return时,只是把return后面的值复制了一份到返回值变量里去了。(总结部分来源于网络)

 验证:

技术分享

由图可知不能通过编译

但是修正代码后得以编译

技术分享

为什么?

throws语句表明某种方法可能出现某种异常,而它自己不能处理,而需要由调用者来处理

 

java异常处理动手动脑问题

标签:多层嵌套   swing   结束   无效   option   oid   异常处理   ...   dex   

原文地址:http://www.cnblogs.com/lovema1210/p/7846186.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!