异常对象都是派生于Throwable类的一个实例
异常结构
Throwable
派生于Error和RuntimeException的称为非受查异常,其他的称为受查异常
// 顶层异常类 public class Throwable implements Serializable {} // Java运行时系统内部错误和资源耗尽 public class Error extends Throwable {} // 异常 public class Exception extends Throwable {} // 运行时异常 public class RuntimeException extends Exception {} // IO异常 public class IOException extends Exception {}
EOFException FileNotFoundException IOException ClassNotFoundException NoSuchFieldException NoSuchMethodException ReflectiveOperationException RuntimeException
ArithmeticException.java ArrayIndexOutOfBoundsException.java ArrayStoreException.java ClassCastException.java EnumConstantNotPresentException.java IllegalArgumentException.java IllegalMonitorStateException.java IllegalStateException.java IllegalThreadStateException.java IndexOutOfBoundsException.java NegativeArraySizeException.java NullPointerException.java NumberFormatException.java SecurityException.java StringIndexOutOfBoundsException.java TypeNotPresentException.java UnsupportedOperationException.java
public FileInputStream(File file) throws FileNotFoundException {}
throw new NullPointerException();
public class ExceptionDemo1 extends Exception { public ExceptionDemo1() { } // 能够打印详细信息 public ExceptionDemo1(String message) { super(message); } }
try { // error } catch() { // process error }
public static void main(String[] args) { try { b(); } catch (Throwable e) { System.out.println("error = " + e.getMessage()); System.out.println("init cause = " + e.getCause()); } } public static void a() { throw new NullPointerException(); } public static void b() throws Throwable { try { a(); } catch (Exception e) { Throwable th = new Exception("b methods error"); // 将e设置为原始异常 th.initCause(e); // 等同于 // Throwable th = new Exception("b methods error", e); throw th; } }
try { } catch() { } finally { }
public static void main(String[] args) { System.out.println(a()); // 2 } static int a() { try { return 1; } finally { return 2; } }
public static void main(String[] args) { try (FileInputStream in = new FileInputStream(""); FileOutputStream out = new FileOutputStream("")) { } catch (Exception e) { } }
public static void main(String[] args) { try { a(); } catch (Exception e) { e.printStackTrace(); System.out.println("--------------"); StackTraceElement[] stackTrace = e.getStackTrace(); Stream.of(stackTrace).forEach(System.out::println); } } static void a() { throw new NullPointerException(); } java.lang.NullPointerException at com.java.practice.exception.ExceptionDemo4.a(ExceptionDemo4.java:26) at com.java.practice.exception.ExceptionDemo4.main(ExceptionDemo4.java:16) -------------- com.java.practice.exception.ExceptionDemo4.a(ExceptionDemo4.java:26) com.java.practice.exception.ExceptionDemo4.main(ExceptionDemo4.java:16)