如果類似檔案找不到 ,這種可預期的錯誤狀況便要利用
try ..catch 把錯誤接收起來並做適當的處理
import java.io.*;
public class ExceptionDemo {
public static void main(String[] args) throws FileNotFoundException{
int i =Integer.parseInt("r"); // this is a runtime exception
System.out.println(i);
//using a try catch block to catch checked exception
try {
FileReader fr = new FileReader(new File("xxx.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//or throw out this exception to the caller.
FileReader fr = new FileReader(new File("xxx.txt"));
}
}
Following is a fail case.
public class UnreachableDemo {
public static void main(String[] args){
int [] k =new int []{1,2,3};
for(int i = 0 ; i < k.length+1 ; i++ ){
System.out.println(k[i]);
}
System.out.println("arrive here?");
}
}
Following is a success case.
public class ReachableDemo {
public static void main(String[] args){
int [] k =new int []{1,2,3};
try{
for(int i = 0 ; i < k.length+1 ; i++ ){
System.out.println(k[i]);
}
System.out.println("within a try block , so it is unreachable");
}catch(Exception e){
e.printStackTrace();
}
System.out.println("outside");
}
}
沒有留言:
張貼留言