Java中的异常总结

1.1按照继承关系 分为Error和Exception
Error:大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。常见的有:StackOverflowError OutOfMemoryError
Exception:是程序本身可以处理的异常。太多了 不举例了 在Eclipse中 鼠标放在类名上 Ctrl+T 显示继承关系
RunTimeException:运行时的异常
Other:Exception和其子类中 除了RunTimeException以外的其余异常
1.2 按照是否在编译的时候做检查 可以分为unchecked exception和
unchecked exception:在编译的时候 不用检查的异常
checked exception:在编译的时候 检查的异常 必须cactch 不然无编译已通过

public class Main {
    public static void main(String[] args) {
        Main mMain = new Main();
        try {
            mMain.other();
        } catch (Exception e ) {
            // 必须catch 不然无法编译通过
        }

        // 无须catch 可以編譯運行通過
        mMain.runtimeException();
        mMain.error();
    }

    private void error() throws Error {
        throw new Error("error" );
    }

    private void other() throws Exception {
        throw new Exception("other");
    }

    private void runtimeException() throws RuntimeException {
        throw new RuntimeException("runtimeException");
    }
}
  1. 关于catch中有return finally中的代码如何执行
public class FinaliyTest {
    static int i = 0;

    int testExReturn() throws Exception {
        try {
            testEx1();
            i++;
            System.out.println("try i : " + i);
        } catch (Exception e) {
            i++;
            System.out.println("catch i : " + i);
            return i;
        } finally {
            i++;
            System.out.println("finally i : " + i);
            // case 1
            return i;
        }
        // case 2
        return i;
    }

    void testEx1() throws Exception {
        throw new Exception();
    }

    public static void main(String[] args) {
        FinaliyTest mFinaliyTest = new FinaliyTest();
        try {
            int k = mFinaliyTest.testExReturn();
            System.out.println(k);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(i);
    }
}

Case 1输出
catch i : 1
finally i : 2
2
2
Case 2 输出
catch i : 1
finally i : 2
1
2
总结:
1.finally中的代码始终会运行 即使catch中有return finally中的代码依旧会运行
2.如果finally中有return 则不会执行catch中return

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值