Java异常

本文详细介绍了Java中的异常处理机制,包括try...catch...finally的使用方法及其执行流程,return语句与finally代码块的关系,以及throw和throws的区别与应用。通过具体示例展示了如何在程序中正确地使用这些机制来处理异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、try…catch…finally,其中finally语句不被执行的唯一情况是先执行了用于终止程序的System.exit()方法。exit()用于终止当前的Java虚拟机进程,Java虚拟机所执行的Java程序也随之终止。
2、return语句用于退出本方法。在执行try或catch代码中的return语句时,假如有finally代码块,会先执行inally代码块

package Test;

public class WithReturn {
    public int methodA(int money) throws Exception {
        if (--money <= 0)
            throw new Exception("Out of money");
        return money;

    }

    public int methodB(int money) {
        try {
            System.out.println("Begin");
            int result = methodA(money);
            return result;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return -100;
        } finally {
            System.out.println("Finally");
        }

    }

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        System.out.println(new WithReturn().methodB(1));
    }

}

输出结果:
Begin
Out of money
Finally
-100

3、finally代码块虽然在return之前执行,但finally代码块不能通过重新给变量赋值的方式来改变return返回的值。
4、throw和throws
下面参考自:http://blog.youkuaiyun.com/luoweifu/article/details/10721543

throw

throw是语句抛出一个异常。
语法:throw (异常对象);
如: throw e;

一般会用于程序出现某种逻辑时程序员主动抛出某种特定类型的异常。如:

    public static void main(String[] args) {  
            String s = "abc";  
            if(s.equals("abc")) {  
                throw new NumberFormatException();  
            } else {  
                System.out.println(s);  
            }  
            //function();  
    }  

会抛出异常:

Exception in thread “main” java.lang.NumberFormatException

at test.ExceptionTest.main(ExceptionTest.java:67)

throws

throws是方法可能抛出异常的声明。(用在声明方法时,表示该方法可能要抛出异常)
语法:(修饰符)(方法名)([参数列表])[throws(异常类)]{……}
如: public void function() throws Exception{……}

当某个方法可能会抛出某种异常时用于throws 声明可能抛出的异常,然后交给上层调用它的方法程序处理。如:

    public static void function() throws NumberFormatException{  
            String s = "abc";  
            System.out.println(Double.parseDouble(s));  
        }  

        public static void main(String[] args) {  
            try {  
                function();  
            } catch (NumberFormatException e) {  
                System.err.println("非数据类型不能转换。");  
                //e.printStackTrace();  
            }  
    }  

处理结果如下:

非数据类型不能转换。
throw与throws的比较

●throws出现在方法函数头;而throw出现在函数体。

●throws表示出现异常的一种可能性,并不一定会发生这些异常;throw则是抛出了异常,执行throw则一定抛出了某种异常对象。

●两者都是消极处理异常的方式(这里的消极并不是说这种方式不好),只是抛出或者可能抛出异常,但是不会由函数去处理异常,真正的处理异常由函数的上层调用处理。
好的编程习惯:

●在写程序时,对可能会出现异常的部分通常要用try{…}catch{…}去捕捉它并对它进行处理;

●用try{…}catch{…}捕捉了异常之后一定要对在catch{…}中对其进行处理,那怕是最简单的一句输出语句,或栈输入e.printStackTrace();

●如果是捕捉IO输入输出流中的异常,一定要在try{…}catch{…}后加finally{…}把输入输出流关闭;

●如果在函数体内用throw抛出了某种异常,最好要在函数名中加throws抛异常声明,然后交给调用它的上层函数进行处理。

综合例子

package Test;

public class TestException {
    public TestException() {
    }

    @SuppressWarnings("finally")
    boolean testEx() throws Exception {
        boolean ret = true;
        try {
            ret = testEx1();
        } catch (Exception e) {
            System.out.println("testEx, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx, finally; return value=" + ret);
            return ret;
        }
    }

    boolean testEx1() throws Exception {
        boolean ret = true;
        try {
            ret = testEx2();
            if (!ret) {
                return false;
            }
            System.out.println("testEx1, at the end of try");
            return ret;
        } catch (Exception e) {
            System.out.println("testEx1, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx1, finally; return value=" + ret);
            return ret;
        }
    }

    boolean testEx2() throws Exception {
        boolean ret = true;
        try {
            int b = 12;
            int c;
            for (int i = 2; i >= -2; i--) {
                c = b / i;
                System.out.println("i=" + i);
            }
            return true;
        } catch (Exception e) {
            System.out.println("testEx2, catch exception");
            ret = false;
            throw e;
        } finally {
            System.out.println("testEx2, finally; return value=" + ret);
            return ret;
        }
    }

    public static void main(String[] args) {
        TestException testException1 = new TestException();
        try {
            testException1.testEx();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.exit(0);
    }
}

输出结果:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值