详解throws方式
1.语法:
throws+异常类型
1⃣️写在方法的声明处。指出此方法执行时,可能会抛出的异常类型。一旦当方法体执行时,出现异常,仍会在异常代码处生成一个异常类的对象。此对象满足throws后异常类型时,就会被抛出。异常代码后面的代码就不会再执行了。
2⃣️try-catch-finally:真正将异常给处理掉了。
throws的方式只是将异常抛给了方法的调用者,并没有真正将异常处理掉。
public class ExceptionTest2 {
public static void main(String[] args){
CC cc=new CC();
try {
cc.method2();
}catch (IOException e){
e.printStackTrace();
}
// cc.method3();
}
}
class CC{
public static void method1() throws FileNotFoundException, IOException {
File file = new File("hello.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while (data != -1) {
System.out.print((char) data);
data = fis.read();
}
fis.close();
}
public static void method2() throws IOException{ //IOException是
// FileNotFoundException的父类
method1();
}
public static void method3(){
try {
method2();
}catch (IOException e){
e.printStackTrace();
}
}
}