黑马程序员——异常总结
在 Java 中,所有的异常都有一个共同的祖先 Throwable(可抛出)
Throwable: 有两个重要的子类:Exception(异常)和 Error(错误),二者都是 Java 异常处理的重要子类,各自都包含大量子类。
Error(错误):是程序无法处理的错误,表示运行应用程序中较严重问题。大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。
Exception(异常):是程序本身可以处理的异常。
注意:异常和错误的区别:异常能被程序本身可以处理,错误是无法处理。
Exception 这种异常分两大类运行时异常和非运行时异常(编译异常)。程序中应当尽可能去处理这些异常。
运行时异常:都是RuntimeException类及其子类异常,如NullPointerException(空指针异常)、IndexOutOfBoundsException(下标越界异常)等,这些异常是不检查异常,程序中可以选择捕获处理,也可以不处理。这些异常一般是由程序逻辑错误引起的,程序应该从逻辑角度尽可能避免这类异常的发生。运行时异常的特点是Java编译器不会检查它,也就是说,当程序中可能出现这类异常,即使没有用try-catch语句捕获它,也没有用throws子句声明抛出它,也会编译通过。
非运行时异常 (编译异常):是RuntimeException以外的异常,类型上都属于Exception类及其子类。
异常处理
在 Java 应用程序中,异常处理机制为:抛出异常,捕捉异常。
从方法中抛出的任何异常都必须使用throws子句。
捕捉异常通过try-catch语句或者try-catch-finally语句实现
1 package blogtest4; 2 /* 3 * 自定义异常类 4 */ 5 class EceptionTest1 6 { 7 public static void main(String args[]) 8 { 9 Demo demo = new Demo(); 10 try 11 { 12 demo.div(1,-1,3); 13 } 14 catch(ChuShuException e) 15 { 16 System.out.println(e.toString()); 17 } 18 19 catch (ArithmeticException e) 20 { 21 System.out.println(e.toString()); 22 } 23 catch (ArrayIndexOutOfBoundsException e) 24 { 25 System.out.println(e.toString()); 26 } 27 } 28 } 29 class Demo 30 { 31 public int div(int a,int b,int c)throws ChuShuException,ArithmeticException,ArrayIndexOutOfBoundsException 32 { 33 int[] arr = new int[]{1,2,3,4}; 34 System.out.println(arr[c]); 35 if(b<0) 36 throw new ChuShuException("chushu wei fushu"); 37 return a/b; 38 } 39 } 40 class ChuShuException extends Exception 41 { 42 ChuShuException(String mes) 43 { 44 super(mes); 45 } 46 }
1 练习 2 package blogtest4; 3 public class EceptionTest2 { 4 /** 5 * 自定义RuntimeExcption子类异常 6 */ 7 public static void main(String[] args) { 8 new RuntimeTest().ChuShu(4,-1); 9 } 10 } 11 class RuntimeExceptionTest extends RuntimeException 12 { 13 RuntimeExceptionTest(String a) 14 { 15 super(a); 16 } 17 18 } 19 class RuntimeTest 20 { 21 int ChuShu(int a,int b) 22 { 23 if(b<0) 24 throw new RuntimeExceptionTest("xiao yu ling"); 25 return a/b; 26 } 27 }