2017-06-12 106 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

相关问题