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

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

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


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

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

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


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

day walker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值