异常处理形式

版权声明:欢迎转载,有问题劳烦指出 https://blog.csdn.net/qq_33592002/article/details/84799892

这时可以对异常进行针对性处理方式
具体格式:
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());
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_33592002/article/details/84799892