【问题标题】:JAVA. I am getting an 'unreported exception' compiler error爪哇。我收到“未报告的异常”编译器错误
【发布时间】:2017-06-12 11:12:19
【问题描述】:

我正在尝试编译这段代码,但一直出错,

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

这个异常是在callmethodErr()中抛出的,我还以为是在main中被抓到了,但是不知道是怎么回事。

谢谢大家。

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();      
    }
  } 
}

【问题讨论】:

  • callmethodErr() 尚未使用 throws Exception 定义,但它确实如此。这肯定很明显吗?
  • 请我提醒您,如果有人帮助了您,接受答案是有礼貌的..

标签: java exception checked-exceptions catch-exception


【解决方案1】:

这个方法:

public static void callmethodErr()
{

包含行:

throw new Exception();          

但没有声明它throws Exception 因此:

public static void callmethodErr() throws Exception
{

【讨论】:

    【解决方案2】:

    Exception 是一个受检异常,这意味着你必须在抛出它的方法中捕获它,或者声明你的方法可能会抛出这个异常。您可以通过更改方法 callmethodErr 的签名来做到这一点,如下所示:

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

    有关其工作原理的更多详细信息,请参阅:Oracle 的 Java 教程中的 The Catch or Specify Requirement

    【讨论】:

      【解决方案3】:

      正如编译器所说,callmethodErr 方法可以抛出异常。因此,您必须在方法callmethodErr 中捕获该异常或声明方法callmethodErr 以抛出异常。是否在 main 方法中捕获它无关紧要,因为您也可以从另一个方法(不是 main)调用方法 callmethodErr 而忘记捕获它,编译器必须防止这种情况发生。

      这样声明方法public static void callmethodErr() throws Exception

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多