JAVA Exception异常总结(JAVA Exception面试笔试总结)

时间:2021-11-05 14:40:05

这方面主要有以下几种类型的题目:

1 try中throw一个exception,能否直接catch?

	public void method1(){
try{
throw new StringIndexOutOfBoundsException("method1 catch");
}catch(Exception e){
System.out.println(e.getMessage());
}
}

解答:这个如果catch里的exception是try中throw的异常或者它的父类,都是可以catch到的。


2.有多个catch的情况,如下,第二个catch是否会catch到?

	/**
* 有多个catch的情况
*/
public void method2(){
try{
throw new StringIndexOutOfBoundsException("method2");
}catch(StringIndexOutOfBoundsException e){
System.out.println("method2 catch 1");
}catch(Exception e){
System.out.println("method2 catch 2");
}
}
解答:catch不管有多少个,也不管catch中的exception是否是父类,只要有一个catch到了,其他的就不会再catch到的


3. catch中throw new exception,下边继续catch能否catch到?

	/**
* catch中throw new exception,下边继续catch能否catch到?
*/
public void method3(){
try{
throw new StringIndexOutOfBoundsException("method3 1");
}catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
throw new StringIndexOutOfBoundsException("method3 2");
}catch(Exception e){
System.out.println(e.getMessage());
}
}
解答:如果这个catch执行的话,抛出了新的异常,就直接报异常导致程序暂停了。下面一个catch不能继续catch到刚才抛出的异常

4.catch中和finally中都throw new exception?

/**
* catch中和finally中都throw new exception
*/
@SuppressWarnings("finally")
public void method4(){
try{
throw new StringIndexOutOfBoundsException("method4 1");
}catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
throw new StringIndexOutOfBoundsException("method4 2");
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
throw new StringIndexOutOfBoundsException("method4 finally");
}
}
解答:最后生效的是finally里的exception.


5.try中执行哪些代码?catch后代码是否执行?

/**
* try中代码执行哪些?try catch 后面代码是否执行?输出什么
*/
public void method5(){
try{
System.out.println("method step1");
new String("abc").subSequence(0, 5);
System.out.println("method step2");
}catch(StringIndexOutOfBoundsException e){
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println(e.getMessage());
}
System.out.println("method step3");
}
解答:这个里里面,try中抛出异常后,try里下面的代码就不执行了,直接进入了catch,如果try中抛出的异常被catch到了,那么catch后面的代码还是继续执行的。

6.异常是否必须catch或者方法头上throw

JAVA Exception异常总结(JAVA Exception面试笔试总结)

看这道题,A 说33行必须放在try中,33行调用method1,此方法中已经catch了testexception,但是又throw了新的RuntimeException,实际上RuntimeException是不用显示捕获的,所以A 错误,B正确

C说方法头上必须声明throw ,也是错误的

D说调用method2时候不用try,这个是不对的,因为throw的TestException不是RuntimeException,因此必须捕获。