Java API 的异常类族
Throwable类
Java语言的异常处理机制
throw语句
向Java虚拟机抛出一个异常对象,其目的是向Java虚拟机报告异常,异常对象必须是throwable类族对象。
基本句型:
异常类名 th = new 异常类名(“异常信息”);
throw th;
简写句型
throw new 异常类名(“异常信息”);
链接句型
throw th;
throw new 异常类名(“附加异常信息”,th);
try-catch语句
测试用例
import java.io.IOException;
public class ExceptionTest {
static void fun(int choice) {
System.out.println("choice"+choice);
System.out.println("before try-catch");
try {
System.out.println("Before throw");
if(choice==1)
throw new ArithmeticException("ArithmeticException");
else if(choice==2)
throw new IOException("IOException");
System.out.println("After throw");
}
catch(ArithmeticException e) {
System.out.println(e.getMessage());
}
catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
System.out.println("finally block");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
fun(1);
}
}
异常
系统异常
系统异常类:Error类的子类
程序员无法预见,处理不了
可以处理,也可以不处理
编程异常
编程异常类:RuntimeException类的子类
程序员因该完全杜绝程序中的编程异常
可以处理也可以不处理
用户异常(勾选异常)
用户异常类:Exception类下除RuntimeException之外的其他子类
Java语法强制要求添加异常处理机制,否则编译不能通过。
自定义异常类
描述自己程序中的特定异常情况
例: