Exception 类 与 RuntimeException 类有什么区别呢?
有以下一道程序
public class RuntimeExceptionDemo01{public static void main(String args[]){String str = "123" ; // 定义字符串,全部由数字组成int temp = Integer.parseInt(str) ; // 将字符串变为int类型System.out.println(temp * temp) ; // 计算乘方}
};
从程序中发现,parseInt() 方法由 Integer类直接调用,说明此方法为静态方法,查看JDK文档,此方法定义如下:
提问:以上的方法使用了 throws 关键字声明,但是在方法调用时并没有进行 try...catch处理,这是为什么呢?
观察 NumberFormatException 类的继承结构:
从中可以发现,NumberFormatException 类是 RuntimeException 类的子类
Exception 类 与 RuntimeException 类的区别:
Exception 在程序中必须使用 try...catch进行处理
RuntimeException 可以不使用try...catch进行处理,如果有异常产生,则异常将由 JVM 进行处理