26 异常

26 异常

定义

程序中运行时出现的错误

分类

从是否主动产生可分为:

1.java中已经预定义好的异常(ArrayIndexoutofException和nullPointerException)
2.自行定义的异常(如AgeException)

从开发者角度可分为:

1.Exception异常(程序中出现的错误)

2.Error异常(JVM错误,程序无法处理)

补充:Throwable类是Exception和Error的父类

处理异常的机制

1.捕捉异常(try.......catch)-------主动

try{
  //可能发生异常的语句
}catch(异常类 异常对象){
  //异常处理语句
}catch(异常类 异常对象){
  //异常处理语句
}finally{
    //调用try catch时一定会执行的代码,不管你在try所在的普通代码块中有没有产生异常
}
//异常处理语句可以有很多即catch{}可以续写很多次
public class ExceptionDemo1{
  public static void main(String args[]){
     int i=10;
     int j=0;
     try{
       int trmp=i/j;
       System.out.println("程序没有出现异常");
     }catch(ArithmeticException e){
       System.out.println("出现异常了: "+e);
     }finally{
       System.out.println("try---catch--finally操作处理完毕!!!");
     }
  }
}

2.交给方法调用处处理

​ throws

public 返回值类型 方法名称(参数1,参数2......参数n) throws Exception{
   
}
public class A{
   public void print() throws Exception{
       int i=10;
       int j=0;
       int trmp=i/j;
       System.out.println("程序没有出现异常");
   }  
}
//类A中print()方法出现的异常(运行错误)会丢给调用 类A print()方法处处理
public class ExceptionDemo1{
  public static void main(String args[]){
     A a=new A();
     a.print();//异常在这里一定得处理,不然会报错
  }
}

注意:理论上任何方法都可以抛异常,但不建议在main函数中抛异常,因为这个时候它会把异常交给jvm处理,得不到任何有效的异常信息了.

3.抛出异常

throw new Exception("自己抛的异常");
//抛出异常时直接抛出异常的实例化对象即可
//这个新抛出的异常也需要处理

4.面试题补充

RuntimeException和Exception的区别,请列举几个常见的RunTimeException

(1)RuntimeException是Exception的子类

(2)Exception定义了必须处理的异常,而RunTimeException定义的异常可以选择型处理

(3)常见的RunTimeException:

​ a. NumberFormatException、

​ b. ClassCastException、

​ c. NullPointerException

​ d. ArithmeticException、

​ e. ArrayIndexOutOfBoundsException

原文地址:https://www.cnblogs.com/SSSzhanglingzhi/p/14063720.html