一、异常抛出介绍
1、在定义一个方法的时候,如果并不能确定如何处理其中可能出现的异常,可以将可能发生的异常让这个方法的调用者来处理;
2、可以对下列情形在方法定义中抛出异常:
-
方法中调用了一个会抛出“已检查异常”的方法;
-
程序运行过程中发生了错误,并且用
throw
子句抛出了一个已检查异常
;
3、不要抛出如下异常:
-
从
Error
中派生的那些异常; -
从
RuntimeException
中派生的那些异常,如NullPointerException
等;
4、捕获异常和抛出异常的方式,并不是排它的,它们可以结合起来使用;
二、语法
<modifer> <returnType> methodName([<argument_list>]) throws <exception_list> {
//statements
}
三、编程实战
代码的详细解读,可以参考视频教程
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* User: 祁大聪
*/
public class S22 {
public static void readFile() throws IOException {
String filePath = "E://a.log";
FileInputStream fis = new FileInputStream(filePath);
byte[] b = new byte[1024];
while(fis.read(b) != -1){
}
}
public static void myException() throws Exception{
boolean flag = false;
if(flag == false){
throw new RuntimeException();
}
}
public static void main(String[] args) {
try {
myException();
} catch (Exception e) {
e.printStackTrace();
}
try {
readFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}