异常
分类
- 检查性异常
代表为用户错误或问题引起的异常,这是程序员无法预见的异常。例:打开一个不存在文件,这些异常无法在编译时被简单忽略。 - 运行时异常
运行时异常是可能被程序员避免的异常,与检查性异常相反,运行时异常可以在编译时被忽略。 - 错误Error
错误不是异常,而是脱离程序员控制的问题,在代码中通常被忽略。例:程序运行时,栈溢出,错误发生,编译时无法检查到。
异常处理框架
定义一个基类java。lang。Throwable作为所有异常的超类
异常类分为两大类:错误Error和Exception
异常处理机制
抛出异常
捕获异常
异常处理:五个关键字
try catch finally throw throws
//Ctrl+Alt+T 自动生成对应的异常捕获
public class demo01 {
static void main(String[] args) {
int a=1;
int b=0;
//System.out.println(a/b);
try{//try监控区域
if(b==0){
throw new ArithmeticException();//主动抛出异常
}
System.out.println(a/b);
}catch(ArithmeticException e){
//catch(需要捕获的异常类型)捕获异常 若有异常则执行catch内语句,若无异常则执行try内语句
//e为exception
System.out.println("程序异常");
}catch(Error e){
System.out.println("Error");
}catch (Exception e){
System.out.println("Exception");
e.printStackTrace();//打印错误的栈信息
}catch (Throwable t){
System.out.println("Throwable");
}finally {//非必需,处理善后工作
System.out.println("finally");
}
System.out.println("===================");
try{
new demo01().test(1,0);
}catch(ArithmeticException e){
e.printStackTrace();
}
}
//异常与错误的捕获需要层层递进,从小到大
//若前面的catch已经执行,则后续不再执行
public void a(){
b();
}
public void b(){
a();
}
public void test(int a,int b) throws ArithmeticException{
if(b==0){
throw new ArithmeticException();
//主动抛出异常,一般在方法中用于检测
}
}
}

浙公网安备 33010602011771号