Java的异常被分为两大类:Checked异常和Runtime异常(运行时异常)。
• Runtime异常:所有的RuntimeException类及其子类的实例;
• Checked异常:不是RuntimeException类及其子类的异常实例。
只有Java语言提供了Checked异常,其他语言都没有提供Checked异常。Java认为 Checked异常都是可以被处理(修复)的异常,所以Java程序必须显式处理Checked 异常。如果程序没有处理Checked异常,该程序在编译时就会发生错误,无法通过编译。
Checked异常体现了Java的设计哲学:没有完善错误处理的代码根本就不会被执行!
Runtime异常则更加灵活,Runtime异常无须显式声明抛出,如果程序需要捕获 Runtime异常,也可以使用try…catch块来实现。
一.使用throws抛出异常
使用throws声明抛出异常的思路是,当前方法不知道如何处理这种类型的异常,该异常应该由上级调用者处理;如果main方法也不知道如何处理这种类型的异常,也可以使用throws声明抛出异常,该异常将交给JVM处理。JVM对异常的处理方法是,打印 异常的跟踪栈信息,并中止程序运行。
如下示例:
public class ThrowsDemo {
public static void main(String[] args) {//throws Exception 虚拟机在处理
// 数组索引越界 ArrayIndexOutOfBoundsException
//String[] strs = {"1"};
// 数字格式异常 NumberFormatException
//String[] strs = {"1.8,1"};
// 算术异常(除零) ArithmeticException
String[] strs = {"18","0"};
//intDivide(strs);//虚拟机在处理
try {//当 main 方法也不想处理,把异常抛出去,就是java 虚拟机在处理
intDivide(strs);
} catch (Exception e) {
System.out.println("main 异常处理");
e.printStackTrace();
}
}
public static void intDivide(String[] strs)throws
ArrayIndexOutOfBoundsException,
IndexOutOfBoundsException,
NumberFormatException,
ArithmeticException{
int a = Integer.parseInt(strs[0]);
int b = Integer.parseInt(strs[1]);
int c = a/b;
System.out.println("结果是:"+c);
}
}
结果如下:
二.使用throw抛出异常
Java也允许程序自行抛出异常,自行抛出异常使用throw语句来完成(注意此处的 throw没有后面的s)。
如果需要在程序中自行抛出异常,则应使用throw语句,throw语句可以单独使用, throw语句抛出的不是异常类,而是一个异常实例,而且每次只能抛出一个异常实例。
如下示例:
public class ThrowDemo {
public static void main(String[] args) {
//数组索引越界 ArrayIndexOutOfBoundsException
String[] str1 = {"1"};
// 数字格式异常 NumberFormatException
//String[] str2 = {"1.8,1"};
// 算术异常(除零) ArithmeticException
//String[] str3 = {"18","0"};
try {
intDivide(str1);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void intDivide(String[] str0) throws Exception{
try {
int a = Integer.parseInt(str0[0]);
int b = Integer.parseInt(str0[1]);
int c = a/b;
System.out.println("结果是:"+c);
}catch (ArrayIndexOutOfBoundsException e) {
throw new Exception("数组索引越界");
}catch (IndexOutOfBoundsException e) {
throw new Exception("索引越界");
}catch (NumberFormatException e) {
throw new Exception("数字转换失败");
}catch (ArithmeticException e) {
throw new Exception("计算错误");
}
catch (Exception e) {
System.out.println("其他异常");
e.printStackTrace();
}
if (str0.length<2) {
//自行抛出 Exception异常
//该代码必须处于try块里,或处于带 throws声明的方法中
throw new Exception("参数个数不够");
}
if (str0[1]!=null && str0[1].equals("0")) {
//自行抛出 RuntimeException异常,既可以显式捕获该异常
//也可完全不理会该异常,把该异常交给该方法调用者处理
throw new RuntimeException("除数不能为0");
}
int a = Integer.parseInt(str0[0]);
int b = Integer.parseInt(str0[1]);
int c = a/b;
System.out.println("结果为:"+c);
}
}
结果如下: