1.分类
Error :错误
Exception:异常
2.异常处理机制
1.try catch finally //程序会正常使用不会中途停止
int a = 1;
int b = 0;
try{
//对范围内的代码进行监控
System.out.println(a/b);
}
catch(ArithmeticException e){
//catch(想要捕获的异常类型)
//如果将类型改为Throwable可以捕获所有类型的异常
//异常只会被捕获一次,无法被捕获多次
System.out.println("出现异常");
}
finally{
//始终执行
}
2. throw throws
//假设方法处理不了这个异常
public void test(int a,int b) throws ArithmeticException
{
if(b==0)
throw new ArithmeticException();//主动抛出异常,一般在方法中使用
}
//如果在方法层面用throws,throw抛出了异常,在调用该方法时就要用到try catch,即抛出的异常总要去捕获
3.自定义异常
public class MyException extends Exception{
private int detail;
//传递数字大于10
pubblic MyException(int a)
{
this.detail = a;
}
//以下为当用try catch 捕获到异常之后打印的信息 即变量e
@Override
public String toString{
return "Myexception" + detail;
}
}