天天看点

浅谈Java异常原理

作者:不秃头程序员
浅谈Java异常原理
异常机制是指当程序出现错误后,程序如何处理。具体来说,异常机制提供了程序退出的安全通道。当出现错误后,程序执行的流程发生改变,程序的控制权转移到异常处理器。

程序错误分为三种:

  • 编译错误
  • 运行时错误
  • 逻辑错误

(1)编译错误是因为程序没有遵循语法规则,编译程序能够自己发现并且提示我们错误的原因和位置,这个也是大家在刚接触编程语言最常遇到的问题。

(2)运行时错误是因为程序在执行时,运行环境发现了不能执行的操作。

(3)逻辑错误是因为程序没有按照预期的逻辑顺序执行。异常也就是指程序运行时发生错误,而异常处理就是对这些错误进行处理和控制。

1 异常分类

浅谈Java异常原理

在 Java 中,异常分为两种:已检查和未检查(即必须捕获的异常和不必捕获的异常)。默认情况下,必须捕获所有异常。

2 异常原理

使用异常的代码:

class ExceptionExampleOriginal {

    public static void main(String[] args) {
        System.out.println("main 方法开始");
        try {
            System.out.println("main 调用前");

            method1();

            System.out.println("main 调用后");
        }
        catch (RuntimeException e) {
            String s = e.getMessage();
            System.out.println(s);
        }
        System.out.println("main 方法结束");
    }

    public static void method1() {
        System.out.println("method1 开始");
        method2();
        System.out.println("method1 结束");
    }

    public static void method2() {
      System.out.println("method2");
      String s = "消息:未知异常";
    throw new RuntimeException(s);

    }
}           

原理的大概表示:

public class ExceptionExample {


    private static Exception exception = null;

   public static void main(String[] args) {
        System.out.println("main 方法开始");

        System.out.println("main 调用前");

        method1();

        if (exception == null) {
            System.out.println("main 调用后");
        }
        else if (exception instanceof RuntimeException) {
            RuntimeException e = (RuntimeException) exception;
            exception = null;
            String s = e.getMessage();
            System.out.println(s);
        }
        System.out.println("main 方法结束");
    }

    public static void method1() {
        System.out.println("method1 开始");
        method2();
        if (exception != null) return;
        System.out.println("method1 结束");
    }

    public static void method2() {
        System.out.println("method2");
        String s = "消息:未知异常";
        exception = new RuntimeException(s);
        return;
    }
}           

“在第一个的示例中,依次调用了一些方法。在 method2 中,特意创建并抛出一个异常(创建了一个错误)。”

“ method2。并不创建异常,而是创建了 RuntimeException 对象,将其保存为 static 变量 exception,然后使用 return 语句立即退出方法。”

“在 method1 中,调用 method2 后,我们检查是否有异常。如果有异常,则 method1 立即结束。在 Java 中,每个方法调用之后,都会间接执行这样的检查。”

“在第二个实例中,使用 main 方法大致显示了使用 try-catch 结构捕获异常时发生的情况。如果没有异常,那么一切将继续正常运行。如果存在异常,并且与 catch 语句中指定的类型相同,则将对其进行处理。”