异常处理形式

这时可以对异常进行针对性处理方式
具体格式:
try{
// 需要被检测异常的代码
}
catch(异常类 变量){
//处理异常的代码
}finally{
//一定会被执行的代码
}
异常处理的原则

  1. 函数内容如果抛出需要检测的异常,那么函数上必须要声明
    否则必须在函数内用try catch捕获,否则编译失败
  2. 如果调用了声明异常的函数,要么trycatch要么throws,否则编译失败
  3. 什么时候trycatch,什么时候throws?
    • 功能内容可以解决,用catch
    • 解决不了,用throws告诉调用者,由调用者处理。
  4. 如果一个功能抛出了多个异常,那么调用时,必须有对应多个catch进行对应的处理
  5. 内部有几个要检测的异常,就抛出几个,就 catch几个
class FuShuIndexException extends Exception{
	FuShuIndexException() {}
	FuShuIndexException(String msg){
		super(msg);
	}
}

class Demo{
	public int method(int[] arr, int index) throws FuShuIndexException{
		if (arr == null)
			throw new NullPointerException("数据的引用不能为空");
		if (index >= arr.length){
			throw new ArrayIndexoutofBoundsException("数组的角标越界拉,跟哥们是不是疯了");
		}
		if (index < 0){
			throw new FuShuIndexException("角标变成负数啦");
		}
		return arr[index];
	}
}
public class ExceptionDemo4 {
	public static void main(String[] args){
		int[] arr =new int[3];
		Demo d = new Demo();
		try{
		    int num = d.method(arr,2);
		    System.out.println("num = "+num);
		}catch(NullPointerException e){
		    System.out.println(e.toString());
		}catch(ArrayIndexoutofBoundsException e){
		    System.out.println(e.toString());
		}catch(FuShuIndexException e){
		    System.out.println(e.toString());
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

浅墨cgz

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

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

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

打赏作者

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

抵扣说明:

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

余额充值