运行时异常与非运行时异常有什么区别?
运行时异常 RuntimeException 又称为非检查异常 uncheck exception。是 Exception 的子类。
在 Java 中,异常可以分为两种。Error 和 Exception,它们的父类是 Throwable。
Error
一些底层的类出错,无法用 java 程序来解决。例如:内存泄露
Exception
分为 运行时异常 和 非运行时异常。
-
运行时异常是指 RuntimeException 或者它的子类。不需要在方法签名声明抛出运行时异常,同样也不需要在方法体中捕获。
例如:空指针异常 NullPointerException,数组越界异常 IndexOutOfBoundsException…
public class MyNumberException extends RuntimeException { public MyNumberException(String message){ super(message); } } public class Test { public static void main(String[] args){ MyNumberException exception = new MyNumberException("Operand type cannot be integer"); throw exception; // 不需要对异常进行处理 } }
-
非运行时异常是指 Exception 及它的子类中 非RuntimeException 的类,需要程序猿在方法签名声明抛出非运行时异常,交给方法的调用者处理(如果方法调用途中一直交给上层处理,最终会交给 JVM,导致程序终止运行);或者在该方法体中对非运行时异常进行捕获。例如:ClassNotFoundException,IOException…
public class MyNumberException extends Exception {
public MyNumberException(String message){
super(message);
}
}
public class Test {
public static void main(String[] args){
MyNumberException exception = new MyNumberException("Operand type cannot be integer");
try {
throw exception;
} catch (MyNumberException e) {
e.printStackTrace();
}
}
}