java中的异常处理

1、错误处理超类:

    java.lang.Throwable

2、错误类型

Error

  • 有虚拟机生成并抛出,例如栈溢出

Error通常是灾难性的致命错误,一旦出现这些错误,JVM一般会选择终止线程,影响很大;

Exception

   包括运行时异常(RuntimeException) 

  •   ArrayIndexOutOfBoundsException(数组下标越界)
  • NullPointerException(空指针异常)
  • ArithmeticException(算术异常)
  • MissingResourceException(丢失资源)
  • ClassNotFoundException(找不到类)

Exception通常是可以被程序控制和处理的

3、错误捕获关键字

  • try(错误监控区域)
  • catch(捕获并按规则输出定义的异常)

          try…catch…的作用:如果代码进入到try的错误监控区域并产生catch定义的错误,则输出对应catch代码块的内容

  • finally  (无论是否有异常,总会执行finally代码块)

实例

public class Application {
    public static void main(String[] args) {
    int a = 1;
    int b = 0;

    try { 
        System.out.println("我没错");
        System.out.println(a/b);
    }
    catch (Error e){
        System.out.println("error");
    }
    catch (Exception e){
        System.out.println("Exception");
    }
    finally {
        System.out.println("finally");
    }
    }
}

ps:

①try下必须有catch,且可以有多个catch;可以没有finally

②catch(想要捕获的异常类型) 多个catch时,异常会按顺序匹配,进入到对应catch代码块中。因此异常类型若有包含关系时,应从小到大排序,例如:

 try {
        System.out.println("我没错");
        System.out.println(a/b);
    }
    catch (Error e){
        System.out.println("error");
    }
    catch (Exception e){
        System.out.println("Exception");
    }
    catch (Throwable e){
        System.out.println("Throwable");
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值