class throwseg1
{
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
void show2() throws Exception // Why throws is necessary here ?
{
show();
}
void show3() throws Exception // Why throws is necessary here ?
{
show2();
}
public static void main(String s[]) throws Exception // Why throws is necessary here ?
{
throwseg1 o1 = new throwseg1();
o1.show3();
}
}
爲什麼編譯器報告方法show2()
,show3()
和main()
都必須被捕獲或聲明爲什麼調用函數時必須「拋出異常」?
沒有報告異常引發異常
當我刪除這些方法throws Exception
?
@PaulTomblin主要肯定可以聲明拋出異常。如果有,JVM將關閉。這與編譯器允許的那樣接近忽略它。 – Taymon 2012-07-21 03:57:35
當被調用的方法(** Methodod1 **)拋出'Exception'時,我們必須用'throws Exception'來定義調用方法(** Method2 **);如果我們沒有在調用方法中傳遞該異常。這樣做的目的是使** Method2 **的調用方法(** Method3 **)可以通過** Method2 **引發異常,並且您應該在此處理它,否則它可能會中斷您的程序。 – Rito 2017-09-11 02:03:50
同樣,如果** Method3 **沒有在它的主體中處理異常,那麼它必須在其方法定義中定義'throws Exception'來提供它的調用方法。以前的評論__extension_ – Rito 2017-09-11 02:11:25