从入门到放弃的第三周(a'pi)......day.14.。。。。。异常;

 

 

1,异常的概念

 


Exception


2,异常的类层次及分类

 


Exception是所有需要处理的异常的父类
RuntimeException及其子类属于运行时异常(非受检(unchecked)异常)
Exception及其子类(除RuntimeException及其子类)属于受检(checked)异常

 


3,关键字:try catch finally throw throws

 


try{
可能抛出异常的代码
}catch(Excption e){ //捕获异常 可以出现多个catch,捕获的异常应该首先是子类异常,后面才是父类异常
e.printStackTrace(); 在控制台的输出中定位错误
//日志记录
}finally{ //无论是否有异常,finally块都会执行,一般用于关闭资源(File,DataBase)

}

try{
}finally{
}

throw一般与方法中,在某种异常情况发生时,明确抛出一个异常的实例(必须是异常层次中的)
throws 用于方法声明时,表示该方法可能会抛出该异常,可以同时声明多个异常

 



任务:编写方法,有异常直接抛出Exception
1,根据半径计算圆的面积,半径不能为零和负数
2,求若干正整数的平均数,参数不能为负数
3,计算两个整数数组相除,{1,2,3,4,5} / {1,2,2,2,3} ={1,1,1,2,1}
都不能为null,长度一致,除数不能0
建议测试时使用try-catch处理

public class Excep {	
	public int   mianji(int r)throws Exception{
		if (r==0||r<0) {
			System.out.print("cuowu");
			throw new Exception();
		}		
		return (int)Math.PI*r*r;
	}
	public int   pum(int[] x)throws Exception{
		int pum=0;
		int sum=0;
		for(int i=0;i<x.length;i++){
		if (x[i]<0) {
			System.out.print("cuowu");
			throw new Exception();			
		}
		}							
		for(int i=0;i<x.length;i++){
			sum=sum+x[i];			
			}
		return pum=sum/x.length;		
	}
}

public class Test {
	static int sum=0;
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		Scanner scanner=new Scanner(System.in);
             int[] x={-1,213,1,4313,1,414,12};
             Excep excep=new Excep();
      	      System.out.println(excep.pum(x));    	      
	}
}

  

4,受检异常与非受检异常(运行时异常)的区别

 


受检异常:必须显式处理:try--catch,,直接在调用的方法上使用throws
非受检异常:可以不显式处理,也可以显式处理

 

 

5,自定义异常

 


一种的特定的业务异常,一般会自己定义一个特定的异常类

原文地址:https://www.cnblogs.com/suxiao666/p/11379874.html