使用方法
try{
//這區塊為可能發生例外的敘述
}
catch(例外型態 變數名稱)
{
 //這區塊為例外發生的處理
}
finally {
    //這區塊為最後的處理
}

 






public class testException {
public static void main(String[] args) {
//基本型
int x = 5, y = 0;
//有發生Exception
try {
int result = x / y;
System.out.println("結果=" + result);
}
catch (Exception e) {
System.out.println("分母不可為0");
}
finally {
//這區塊為最後的處理 ,可有可無。
System.out.println("測試一結束");
}
//沒有發生Exception
try {

int result = x + y;
System.out.println("1+0結果=" + result);
}
catch (Exception e) {
System.out.println("不可為0");
}
finally {
//這區塊為最後的處理 ,可有可無。
System.out.println("測試二結束");
}
}
}


另外不建議把例外處理故意當做流程控制用。


返回[JAVA]流程控制語法目錄





arrow
arrow

    PG Levin Li 發表在 痞客邦 留言(0) 人氣()