throws + 异常类型
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* @author xianyu
* @version 1.0
* @date 2020/1/1 15:53
*/
public class ExceptionTest2 {
public static void main(String[] args){
// 可以在最终调用时处理
try {
method2();
} catch (IOException e) {
e.printStackTrace();
}
method3();
}
// method3进行了异常处理
public static void method3(){
try {
method2();
} catch (IOException e) {
e.printStackTrace();
}
}
// 这里任然向上抛出异常
public static void method2() throws IOException{
method1();
}
// 异常跑出去,给调用该方法的方法去处理
public static void method1() throws FileNotFoundException,IOException {
File file = new File("hello1.txt");
FileInputStream fis = new FileInputStream(file);
int data = fis.read();
while(data != -1){
System.out.print((char)data);
data = fis.read();
}
fis.close();
}
}
try – catch – finally
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* @author xianyu
* @version 1.0
* @date 2020/1/1 15:35
*/
public class ExcceptionTest {
public static void main(String[] args) {
// 异常测试
String str = "123";
//str = "abc";
int num = 0;
try{
num = Integer.parseInt(str);
}catch (NumberFormatException e){
//System.out.println("出现数值转换异常了");
e.printStackTrace();
}
System.out.println(num);
System.out.println("***************************");
File file = new File("hello.txt");
try {
FileInputStream fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}