trycatch之catch对捕获异常的处理及后续代码的执行的探索
工作时,一直对try块中throw的异常对象,在catch中如何处理此异常,以及trycatchfinally完毕,程序是否就此停止还是继续运行很迷惑,于是参考网上的资料,自己写了些demo,去慢慢探索。
例1.
public static void main(String[] args) {
int i = 7;
int j = 0;
try {
if (j == 0)
throw new ArithmeticException();
System.out.println("打印计算结果i/j=" + i / j);
}
catch (ArithmeticException e) {
System.out.println("被除数j不能等于0");
}
System.out.println("运行结束");
}
run:
被除数j不能等于0
运行结束
结论:可以看到,当try块中创建 ArithmeticException异常对象,并由throw语句将异常抛给Java运行时系统,由系统寻找匹配的异常处理器catch并运行相应异常处理代码,打印 "被除数j不能等于0",然后trycatch块结束,程序继续运行,打印"运行结束".可以看到,throw 异常对象,程序并未结束,而是继续执行。另外,我们在catch块中用输出语句打印信息,并不能很全面,直观,专业的把异常信息给显示出来。
例2.
public static void main(String[] args) {
int i = 7;
int j = 0;
try {
if (j == 0)
throw new ArithmeticException();
System.out.println("打印计算结果i/j=" + i / j);
}
catch (ArithmeticException e) {
e.printStackTrace();
}
System.out.println("运行结束");
}
run:
java.lang.ArithmeticException
at com.westward.Demo4.main(Demo4.java:9)
运行结束
结论:通过catch块中,调用异常对象ArithmeticException的printStackTrace()方法,能够将对应的异常信息打印出来,trycatch块下面的程序继续执行。
例3.
如果我们想在try块中,j==0时,程序抛出异常,并且程序中断,可以继续看下面的demo。
public static void main(String[] args) {
int i = 7;
int j = 0;
try {
if (j == 0)
throw new ArithmeticException();
System.out.println("打印计算结果i/j=" + i / j);
}
catch (ArithmeticException e) {
throw e;
}
System.out.println("运行结束");
}
run:
Exception in thread "main" java.lang.ArithmeticException
at com.westward.Demo4.main(Demo4.java:9)
结论:通过运行结果,我们可以看到,在catch块中throw ArithmeticException对象后,throw语句将异常抛给Java运行时系统,由系统寻找匹配的异常处理器catch,由于未找到相应的异常处理器catch(没有catch或者有catch,但是类型不符合),所以异常最后抛给了jvm,并在后台打印异常信息,程序在此中断,trycatchfinally下面的程序代码不在执行。
附加:事实上,ArithmeticException为RuntimeException(运行时异常,不可查异常)的子类。而运行时异常将由运行时系统自动抛出,不需要程序员使用throw语句显示抛出。
下两例摘自:http://blog.csdn.net/hguisu/article/details/6155636
感觉真是太经典了。
例子1:
public static void main(String[] args) {
int[] intArray = new int[3];
try {
for (int i = 0; i <= intArray.length; i++) {
intArray[i] = i;
System.out.println("intArray[" + i + "] = " + intArray[i]);
System.out.println("intArray[" + i + "]模 " + (i - 2) + "的值: "
+ intArray[i] % (i - 2));
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("intArray数组下标越界异常。");
} catch (ArithmeticException e) {
System.out.println("除数为0异常。");
}
System.out.println("程序正常结束。");
}
run:
intArray[0] = 0
intArray[0]模 -2的值: 0
intArray[1] = 1
intArray[1]模 -1的值: 0
intArray[2] = 2
除数为0异常。
程序正常结束。
相信很多man会和我有一样的疑问,怎么只抛出了ArithmeticException 异常,而未抛出ArrayIndexOutOfBoundsException异常呢?
答案是: 一旦某个catch捕获到匹配的异常类型,将进入异常处理代码。一经处理结束,就意味着整个try-catch语句结束。其他的catch子句不再有匹配和捕获异常类型的机会。也就是说,jvm运行.class文件遇到异常时,只会抛出一种异常,这时这个trycatch块就结束了。上例中,程序首先执行到i=2,除数为0的情况,java运行时程序将ArithmeticException 这个运行时异常抛给对应的catch异常捕捉器,执行异常代码,打印 "除数为0异常。"。然后此trycatch块结束,由于for循环在try块中,所以第4此循环不在执行。所以不会遇到 ArrayIndexOutOfBoundsException。 接着打印 "程序正常结束。"。
例子2:
public static void main(String args[]) {
int i = 0;
String greetings[] = { " Hello world !", " Hello World !! ",
" HELLO WORLD !!!" };
while (i < 4) {
try {
// 特别注意循环控制变量i的设计,避免造成无限循环
System.out.println (greetings[i]);
i++;
System.out.println(i);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界异常");
} finally {
System.out.println("--------------------------");
}
}
}
run:
会死循环。
结论:当i=3的时候,jvm执行到 System.out.println (greetings[i]);@ 会抛异常,被 ArrayIndexOutOfBoundsException捕获,执行catch块里的代码,然后执行finally,然后3<4,然后执行@处代码,然后...原因就是当System.out.println (greetings[i]);抛异常的时候,它下面的代码就不会执行了,所以i会永远等于3,3<4永远成立,进入死循环。
我们可以巧用finally如下例来避免这种情况发生。
public static void main(String args[]) {
int i = 0;
String greetings[] = { " Hello world !", " Hello World !! ",
" HELLO WORLD !!!" };
while (i < 4) {
try {
// 特别注意循环控制变量i的设计,避免造成无限循环
System.out.println (greetings[i]);
System.out.println(i);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组下标越界异常");
} finally {
System.out.println("--------------------------");
i++;
}
}
}
run:
Hello world !
0
--------------------------
Hello World !!
1
--------------------------
HELLO WORLD !!!
2
--------------------------
数组下标越界异常
--------------------------
trycatch之catch对捕获异常的处理及后续代码的执行的探索的更多相关文章
- 35 异常机制 异常处理机制 异常处理五个关键字 try、catch、finally、throw、thorws 代码
异常处理机制 概念 抛出异常 捕获异常 异常处理五个关键字 try.catch.finally.throw.thorws 代码 // main { int a = 1; int b = 0; // 假 ...
- try{...} catch {...} finally{...} 各种情况代码的执行情况
try { int i = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("in the 'try'"); } ca ...
- 异常依然执行{try..catch语句块..}的后续代码
测试异常依然执行{try..catch语句块..}的后续代码: private static Integer testThrows() throws Exception{ Integer result ...
- 当try、catch中有return时,finally中的代码会执行么?
今天,看到一个面试题: try-catch-finally 中,如果 catch 中 return 了,finally 还会执行吗? 我们用代码来验证下: public static void mai ...
- try catch 自定义捕获异常
当我们完成一个程序时,如果没有异常捕获的话,用户使用时会出现许多bug.而加入异常捕获之后便会提醒用户使用时避免产生不必要的错误.具体操作实现如下: 首先创造一个MyException类,继承自Exc ...
- 论try/catch的重要性,我们经常遇到代码出现无法调试的错误,程序退出的时候崩溃。这跟我们代码日常保护的习惯息息相关。
每当构造函数或析构函数中出现溢出,会导致调试非常困难,而使用try/catch来处理构造中的初始化就非常重要了. 如上图,在构造函数中,我们的很多初始化动作会放在这里,但是却忽视了,一旦初始化出错了, ...
- Java 异常处理 try catch finally throws throw 的使用和解读(一)
//最近的一个内部表决系统开发过程中,//发现对异常处理还存在一些模棱两可的地方,//所以想着整理一下//主要涉及到://1.try catch finally throws throw 的使用和解读 ...
- try/catch捕获处理异常
1.throws是中断处理,后续代码不能执行 try/catch方法体之后的后续代码有没有异常都可以继续执行: 2.当try方法体中出现异常才会执行catch方法体中代码
- Java中的异常简介
Java中异常的分类 Java中的异常机制是针对正常运行程序的一个必要补充,一般来说没有加入异常机制,程序也能正常运营,但是,由于入参.程序逻辑的严谨度,总会有期望之外的结果生成,因此加入异常机制的补 ...
随机推荐
- git下载速度太慢【学习笔记】
使用了sshFQ的伙伴添加这个配置下载速度有极大的提升. git config --global http.proxy 'socks5://127.0.0.1:1080'
- ubuntu16.04下firefly rk3288的编译安卓4.4
一.背景 OS: ubuntu 16.04 二.配置交叉编译环境 2.1 安装openjdk sudo apt-get install openjdk-7-jdk 2.2 使在同一台机器上可以编译an ...
- VS2017无法启动程序 操作在当前状态中是非法的
工具--选项--调试--常规--启用asp.net的JavaScript调试(chrome和ie)去掉勾选
- 解决Eclipse 项目报错:Unbound classpath container: ‘JRE System Library [JavaSE-1.7]
MyEclipse出现下面两条报错: The project cannot be built until build path errors are resolved HelloWord Unknow ...
- Sql 最简单的Sqlserver连接
string name = txtUserName.Text.Trim();//移除用户名前部和后部的空格 string pwd = txtUserPwd.Text.Trim();//移除密码前部和后 ...
- Ubuntu 12.04 安装JDK
为了在Ubuntu上安装好eclipse,按照步骤先进行JDK的安装. (1) 新建java文件夹 命令行操作: (2) 下载解压JDK安装包后无法移动文件夹至File System 移动时提示:Pe ...
- 告诉你什么是javascript的回调函数
函数也是对象 想弄明白回调函数,首先的清楚地明白函数的规则.在javascript中,函数是比较奇怪的,但它确确实实是对象.确切地说,函数是用Function()构造函数创建的Function对象.F ...
- python 正则表达式替换字符串中匹配的字符
import re street = '21 Ramkrishna Road' print(re.sub('Road$', 'Rd.', street)) 将结尾的Road用Rd.替换
- Python day10 global关键字、函数递归、匿名函数、map函数的用法详解
1.global关键字 引用全局变量,在局部全局变量改变,也会改变,global相当于指针,将地址指向全局变量的name name='littlepage' def littepage(): glob ...
- signal_windows
1.Qt532(vs2010 opengl) // ZC: windows signal: // http://blog.csdn.net/mergerly/article/details/79521 ...