第一种:捕获异常:
第二种:把“锅”甩给Java
虚拟机:
throw 关键字
throw关键字的作用是:主动抛出异常;
首先我们来看系统自动抛出异常:
public static void main(String[] args) {
int a = 10;
int b = 0;
System.out.println(a/b);
}
运行这段代码系统会自动抛出,java.lang.ArithmeticException
异常。
这段程序使用throw
关键字也可以实现:
public static void main(String[] args) {
int a = 10;
int b = 0;
if(b == 0){
throw new ArithmeticException("/ by zero");
}
System.out.println(a/b);
}
可以发现两段程序的运行结果都类似:
throw
是语句抛出一个异常,一般是在代码块的内部,当程序出现某种逻辑错误时由程序员主动抛出某种特定类型的异常。
注意:使用throw
关键字主动抛出检测性异常的时候,在方法名上必须使用throws
表明调用这个方法可能存在要抛出的异常。
举个例子:
ArithmeticException
属于运行时异常,是在运行时检测的,所以上述代码编译是能通过的,而FileNotFoundException
是属于检测性异常,是在编译之前就需要处理的,所以第二段程序要加上throws
才能通过编译。
package step3;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Task {
/********* Begin *********/
//请在合适的部位添加代码
public static void main(String[] args)throws FileNotFoundException
{
test();
}
public static void test() throws FileNotFoundException{
File file = new File("abc");
if(!file.exists()){ //判断文件是否存在
//文件不存在,则 抛出 文件不存在异常
throw new FileNotFoundException("该文件不存在");
}else{
FileInputStream fs = new FileInputStream(file);
}
}
/********* End *********/
}