1.直接throw 抛出 ,不往下执行
/**
* 直接throw 抛出
*/
public static void main(String[] args) {
String str = null;
System.out.println("before");
checkNotNull(str); //1.直接抛出异常,不往下执行
System.out.println("after");
}
private static void checkNotNull(Object var0) {
if (var0 == null) {
throw new NullPointerException();
}
}
测试示例如下:
2. try catch 捕获异常,往下执行
/**
* try catch 捕获异常,往下执行
*/
public static void main(String[] args) {
String str = null;
System.out.println("before");
try {
checkNotNull(str); // 捕捉异常,往下执行
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after");
}
private static void checkNotNull(Object var0) {
if (var0 == null) {
throw new NullPointerException();
}
}
测试示例如下:
注意补充:
在Java中,异常类的结构层次图如下图所示:
在Java中,所有异常类的父类是Throwable类,Error类是error类型异常的父类,Exception类是exception类型异常的父类,RuntimeException类是所有运行时异常的父类,RuntimeException以外的并且继承Exception的类是非运行时异常。
典型的RuntimeException包括NullPointerException、IndexOutOfBoundsException、IllegalArgumentException等。
典型的非RuntimeException包括IOException、SQLException等。