java基础---->Java中异常的使用(二)

  这一篇博客用例子讲述一下异常的处理过程。那些 我们一直惴惴不安 又充满好奇的未来 会在心里隐隐约约地觉得它们是明亮的。

异常的执行过程

一、实例一:return语句

public class ExceptionTest_1 {
    public static void main(String[] args) {
        int result = 0;
        try {
            System.out.println("before result");
            result = 9 / 0;
            System.out.println("after result");
        } catch (Exception e) {
            System.out.println("exception" + e.getMessage() + ", result: " + result);
            return;
        } finally {
            System.out.println("final execute, " + result);
        }
        System.out.println("out of try statement, " + result);
    }
}

执行的结果如下:

before result
exception/ by zero, result: 0
final execute, 0

将上述代码result = 9 / 0改为 result = 9 / 2;也就是不产生异常,执行的结果如下:

before result
after result
final execute, 4
out of try statement, 4

二、实例二:try里面有try语句

public class ExceptionTest_2 {

    public static void main(String[] args) {
        try {
            if (1 + 2 > 2) {
                throw new FileNotFoundException();
            }
            try {
                throw new FileNotFoundException();
            } catch (FileNotFoundException e) {
                System.out.println("world hello");
            }
        } catch (Exception e) {
            System.out.println("hello world");
        } finally {
            System.out.println("final action");
        }
    }
}

执行的结果如下:

hello world
final action

如果将if(1 + 2 > 2)改变if(1 + 2 > 4),也就是try块里面没有抛出异常。执行的结果如下:

world hello
final action

 简短的异常说明:

当抛出异常后,会发生以下的事情。
1、用new在堆上创建异常对象,当前的执行路径被终止,并从当前环境中弹出异常对象的引用。
2、异常处理机制接管程序,并寻找一个恰当的地方继续执行程序。
3、如果有定义了final,那么会执行final块的代码。

三、自定义异常并定义抛错的信息

public class ExceptionTest {
    @Test
    public void exception_message_test1() {
        throw new ValidateRuntimeException("my name is huhx."); //  调用的是getMessage()方法
    }
}

class ValidateRuntimeException extends RuntimeException {
    public ValidateRuntimeException(String message) {
        super(message);
    }

    @Override
    public String getMessage() {
        String message = super.getMessage();
        System.out.println("message: " + message);
        return message + "hello";
    }
}

上述代码的运行效果如下:为什么会打印了三次呢?

message: my name is huhx.
message: my name is huhx.
message: my name is huhx.

com.linux.huhx.ValidateRuntimeException: my name is huhx.hello

    at com.linux.huhx.ExceptionTest.exception_message_test1(ExceptionTest.java:12)
  ........

友情链接

原文地址:https://www.cnblogs.com/huhx/p/baseusejavaexception2.html