Java异常处理机制

处理的异常分为编译异常和运行异常(编译异常,必须处理<try-catch-finally或是throws二选一>,而对于运行异常,可以不处理,默认throws)

1、先来介绍try-catch-finally,代码语法如下:

try{
    异常代码;
    }catch(Exception e){
        1、系统将异常代码封装为e,传入catch代码块中执行,若没有异常代码,catch代码块不执行
        2、程序员自己可加入代码逻辑
    }finally{
        不管代码是否异常,catch是否执行,finally都会执行
}
温馨其实:如果有异常 但是没处理 也就是try-finally,程序会在执行完finally后直接崩溃 不执行之后的语句

示例

public class SS {
    public static void main(String[] args){
        try {
            int a = 30;
            int b = 0;
            int c = a/b;
            System.out.println(c);
        }
        catch (Exception e) {
            System.out.println("异常处理:" + e.getMessage());
        }
        finally {
            System.out.println("第一个异常结束");
        }

        try {
            int c = 18;
            int d = 2;
            int e = c/d;
            System.out.println(e);
        } catch (Exception exception) {
            System.out.println("异常处理:" + exception.getMessage());
        } finally {
            System.out.println("第2个异常结束 ");
        }
        try {
            Person p = new Person();
            p = null;
            System.out.println(p.getClass());
        } finally {
            System.out.println("第3个异常 程序还在执行");
        }
        System.out.println("程序还执行吗");
    }
}
class Person{

}

运行结果:

最后一个异常为空指针异常,没有用catch处理,则执行完finally程序崩溃,不执行下面的代码,所以最后一个输出语句没有输出

2、throws:

假设代码运行时 调用关系如图所示

throws运行机制如下:

程序从上往下运行,运行到4步发现有异常,这时有两种选择 一种是try-catch-finally,另外一种是throws,选t-c-f就会解决异常,但选择throws时会将异常抛出到上一步也就是第3步,同样地,第3 步也会有上述两种选择,以此类推,一直抛到jvm,这时jvm发现异常抛回他会选择不进行处理,终止程序。

示例:

public class SS {
    public static void main(String[] args) {
        A a = new A();
        a.f1();
    }
}
class A {
    public void f1() throws ArithmeticException{//方法内为运行异常,可以不处理,程序会自动throws
        int a = 16;
        int b = 4;
        int c = a/b;
        System.out.println(c);
        }
}
class F extends A{
    public void f1() throws ArithmeticException{//这里要么和父类一样,要么是父类的子类

    }
}
温馨提示:子类的异常类型必须和父类的异常类型一致,或是父类异常类型的子类
当然也可以不写
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值