一篇文章带你搞定 Exception 类与 RuntimeException 类的关系

338 阅读1分钟
public class Test{
    public static void main(String[] args) {
        String str = "123";
        int temp = Integer.parseInt(str);
        System.out.println(temp * temp);
    }
}

由代码可以看出,Integer 因为开头首字母大写,所以肯定是一个类,而 parseInt() 方法可以直接由类名称调用,所以此方法肯定是一个静态方法,此方法定义:

public static int parseInt(String s) throws NumberFormatException;

这里在方法中使用了 throws 关键字,但是在方法调用时并没有使用 try...catch进行处理 观察 NumberFormatException 类的继承关系: 在这里插入图片描述

由图可以知道 NumberFormatException 属于 RuntimeException 的子类

Exception 在程序中必须使用 try...catch 进行处理

RuntimeException 可以不使用 try...catch 进行处理,但是如果有异常产生,则异常将由 JVM 进行处理

虽然 RuntimeException 的异常可以不用 try...catch 进行处理,但是如果一旦出现异常,则肯定会导致程序中断执行,所以为了保证程序在出错后依然可以执行,在开发代码时最好使用 try...catch 的异常处理机制进行处理