當前位置:編程學習大全網 - 源碼下載 - JAVA如何拋出異常?

JAVA如何拋出異常?

如果妳知道妳寫的某個函數有可能拋出異常,而妳又不想在這個函數中對異常進行處理,只是想把它拋出去讓調用這個函數的上級調用函數進行處理,那麽有兩種方式可供選擇:

第壹種方式:直接在函數頭中throws SomeException,函數體中不需要try/catch。比如將最開始的例子中的testEx2改為下面的方式,那麽testEx1就能捕捉到testEx2拋出的異常了。

boolean testEx2() throws Exception{

boolean ret = true;

int b=12;

int c;

for (int i=2;i>=-2;i--){

c=b/i;

System.out.println("i="+i);

}

return true;

}

第二種方式:使用try/catch,在catch中進行壹定的處理之後(如果有必要的話)拋出某種異常。例如上面的testEx2改為下面的方式,testEx1也能捕獲到它拋出的異常:

boolean testEx2() throws Exception{

boolean ret = true;

try{

int b=12;

int c;

for (int i=2;i>=-2;i--){

c=b/i;

System.out.println("i="+i);

}

return true;

}catch (Exception e){

System.out.println("testEx2, catch exception");

Throw e;

}

}

第三種方法:使用try/catch/finally,在catch中進行壹定的處理之後(如果有必要的話)拋出某種異常。例如上面的testEx2改為下面的方式,testEx1也能捕獲到它拋出的異常:

boolean testEx2() throws Exception{

boolean ret = true;

try{

int b=12;

int c;

for (int i=2;i>=-2;i--){

c=b/i;

System.out.println("i="+i);

throw new Exception("aaa");

}

return true;

}catch (java.lang.ArithmeticException e){

System.out.println("testEx2, catch exception");

ret = false;

throw new Exception("aaa");

}finally{

System.out.println("testEx2, finally; return value="+ret);

}

}

  • 上一篇:源代碼透析
  • 下一篇:電腦遊戲術語大觀
  • copyright 2024編程學習大全網