Excepiton分两类:checked exception、runtime exception;直接继承自Exception就是checked exception,继承自RuntimeException就是runtime的exception。
你可以简单地理解checked exception就是要强制你去处理这个异常(不管你throws多少层,你终归要在某个地方catch它);而runtime exception则没有这个限制,你可以自由选择是否catch。
那些强制异常处理的代码块,必须进行异常处理,否则编译器会提示“Unhandled exception type Exception”错误警告。
举例子:
IndexOutOfBoundsException是RuntimeException的一种,方法体内手动throw了一个异常,但是rangeCheckForAdd()定义处不用写 throws……
而getName()则必须要throws
private static void rangeCheckForAdd(int index) {
// IndexOutOfBoundsException是RuntimeException的一种,方法体内手动throw了一个异常,test7_throw()定义处不用写 throws
int size = 3;
if (index > size || index < 0) {
throw new IndexOutOfBoundsException();
}
}
private static void getName() throws IOException { // 这里的throws必须写
// FileNotFoundException是checkedException的一种,直接继承自Exception
// 那些强制异常处理的代码块,必须进行异常处理,否则编译器会提示“Unhandled exception type Exception”错误警告
throw new FileNotFoundException();
}