前言:
大家好,这次我给大家分享一些关于异常的运行结果类型题,做题思路和分析为了方便大家阅读都写在注释里了。
目录
第一题:
class Exc0 extends Exception {
}
class Exc1 extends Exc0 {
}
public class LianXi6 {
public static void main(String[] args) {
try {
throw new Exc1();
} catch (Exc0 e) {//将小网放前面,大网放后面就能捕捉漏小网之鱼
System.out.println("Exc0");
} catch (Exception e) {//Exception好比一张大网,将所有异常、包括它的子类异常都捕捉了,如果小网放后面捕捉Exc1异常就没有意义了。
System.out.println("Exception");
}
}
}
第二题:
class Test {
public static String output = "";
public static void foo(int i) {
try {
if (i == 1) {
throw new Exception();
}
output += "1";//1
} catch (Exception e) {
output += "2";//3//13423
return;
} finally {
output += "3";//13//1342
}
output += "4";//134
}
public static void main(String args[]) {
foo(0);
System.out.println(output);//134
foo(1);//output是全局变量,第一个foo方法改变了output的值为134.
System.out.println(output);//13423
}
}
第三题:
public class ReturnExceptionDemo {
static void methodA() {
try {
System.out.println("进入方法A");//输出
throw new RuntimeException("制造异常");//抛出异常前执行finally语句,之后输出
} finally {
System.out.println("用A方法的finally");//输出
}
}
static int methodB() {
try {
System.out.println("进入方法B");//输出
// throw new Exception();
return 1;//返回之前执行finall语句,然后返回值为1
} catch (Exception e) {
return 3;
} finally {
System.out.println("调用B方法的finally");//输出
// return 2;
}
}
public static void main(String[] args) {
try {
methodA();
} catch (Exception e) {
System.out.println(e.getMessage());
}
int i = methodB();
System.out.println(i);//输出
}
}
所以该题的运行结果为:
进入方法A
用A方法的finally
制造异常
输出异常信息
进入方法B
调用B方法的finally
1