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中的异常机制是针对正常运行程序的一个必要补充,一般来说没有加入异常机制,程序也能正常运营,但是,由于入参.程序逻辑的严谨度,总会有期望之外的结果生成,因此加入异常机制的补 ...
随机推荐
- C# 取form表单的数据
//key代表form表单中html元素的name属性值 public static string StringForm(string key) { string result = null; res ...
- Python3基础 ** 幂运算 // 整除运算
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- win7 64位debug解决方法
1.下载win 64位的DOSBox,如DOSBox0.74: 2.下载win 32 debug.exe,并复制到调用的目录,如d盘根目录d:\ 3.安装DOSBox,并运行:如下图: 4.键入命令: ...
- 打开vi后提示The ycmd server SHUT DOWN (restart with :YcmRestartServer)该如何处理
答:进入YouCompleteMe的安装目录安装一些必要的依赖 比如:笔者将YouCompleteMe安装到了~/.vim/bundle目录下,那么执行以下操作: cd ~/.vim/bundle/Y ...
- Maximum GCD (stringstream)题解
Given the N integers, you have to find the maximum GCD (greatest common divisor) of every possiblepa ...
- Luogu 2671 求和 NOIP2015T3
题目链接 题解 20pts $O(n^3)$枚举$x,y,z$,根据题目要求判断 40pts $O(n^2)$枚举$x,z$,需要满足$x,z$奇偶相同 20~40pts的代码我都没有写过...就不贴 ...
- ZOJ 3469 Food Delivery(区间DP)
https://vjudge.net/problem/ZOJ-3469 题意:在一条直线上有一个餐厅和n个订餐的人,每个人都有随时间上升的不满意值,从餐厅出发,计算出送完时最小的不满意值总和. 思路: ...
- django 数据库同步
python manage.py makemigrations python manage.py migrate
- c++ 匹配相邻元素相等的元素(adjacent_find)
#include <iostream> // cout #include <algorithm> // adjacent_find #include <vector> ...
- kali 下程序卸载方法
ali中主要为2种卸载方法:1.apt2.dpkg 使用apt的方式有:apt-get remove [package]apt-get remove --purge # ------(package ...