java使用try-catch語句來處理異常,將可能出現的異常操作放在try-catch語句的try部分,一旦try部分拋出異常,或調用某個可能拋出異常的方法,並且該方法跑出了異常對象,那麼try部分將立刻結束執行,專項執行相應的catch部分,所以程序可以將發生異常後的處理放在catch中,try-catch語句可以有多個catch組成,分別處理髮生的相應異常,
public class TryCatchFinally {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TryCatchFinally tcf=new TryCatchFinally();
int result=tcf.Test();
System.out.println("result爲:"+result);
System.out.println("test方法執行完畢");
}
/**
* divider();
* result();
* try-catch鋪貨while循環
* 每次循環,divider減一,result=result+100
* 如果:鋪貨異常,打印輸出“捕獲異常了”
* 否則:返回result
* @return
*/
public int Test(){
int divider=10;
int result=100;
try{
while(divider>-1)
{divider--;
result+=100/divider;}
return result;
}
catch(Exception e){
System.out.println("拋出異常了");
return -1;
}
//finally(){}
}
}