2017-06-12 104 views
0

我試圖編譯這段代碼,但它一直有一個錯誤,JAVA。我得到一個「未報告的異常」編譯器錯誤

errThrower.java:37: error: unreported exception Exception; must be caught or declared to be thrown 
throw new Exception(); 

,拋出此異常在callmethodErr(),而且我認爲這已經被抓主要的,但我無法弄清楚發生了什麼。

謝謝大家。

import java.util.IllegalFormatConversionException; 

public class errThrower 
{ 
    public static void main(String[] args) 
    { 
    try 
    { 
     callmethodErr(); 
    } 
    catch (Exception e) 
    { 
     e.printStackTrace(); 
    } 
    } 

    public static void methodErr() throws Exception 
    { 
    System.out.println("error thrown from methodErr"); 
    } 

    public static void callmethodErr() 
    { 
    try 
    { 
     methodErr(); 
    } 
    catch (Exception e) 
    { 
     System.out.println("error thrown from callMethodErr"); 
     throw new Exception();  
    } 
    } 
} 
+0

'callmethodErr()'尚未與所定義的方法'拋出Exception',但它確實。這當然很明顯? – EJP

+0

請讓我提醒你,如果有人幫助你,接受答案是禮貌的。 – Stewart

回答

2

這種方法:

public static void callmethodErr() 
{ 

包含行:

throw new Exception();   

但並沒有聲明這throws Exception這樣的:

public static void callmethodErr() throws Exception 
{ 
1

Exception是檢查異常,然後意味着您必須在所引發的方法中捕獲它,或者聲明您的方法可能會拋出此異常。你可以通過改變你的方法callmethodErr的簽名是這樣的:

public static void callmethodErr() throws Exception 
{ 
    // ... 
} 

對於如何工作的,看到更多的細節描述:The Catch or Specify Requirement在甲骨文的Java教程。

1

正如編譯器所說,方法callmethodErr可以拋出一個異常。因此,您必須在方法callmethodErr中捕獲該異常,或者聲明方法callmethodErr來拋出異常。無論您是否在主要方法中捕捉它都不相關,因爲您也可以從另一種方法(而不是主要方法)調用方法callmethodErr並忘記捕獲它,編譯器必須阻止這種方法。

聲明這樣public static void callmethodErr() throws Exception

相關問題