搜尋此網誌

2012年3月11日 星期日

Java exception -例外處理

Runtime exception: 非程式設計師所能預期到的錯誤.可直接拋出.

如果類似檔案找不到 ,這種可預期的錯誤狀況便要利用

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");
}
}

Java action listener

Inner Class implementation:



Change getHelloButton with follwing example, you will get an anonymous version implementation: