繁体   English   中英

JAVA。 我收到“未报告的异常”编译器错误

[英]JAVA. I am getting an 'unreported exception' compiler error

我正在尝试编译此代码,但它始终出现错误,

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

该方法:

public static void callmethodErr()
{

包含以下行:

throw new Exception();          

但不声明因此throws Exception

public static void callmethodErr() throws Exception
{

Exception是一个已检查的异常,这意味着您必须在引发该异常的方法中捕获它,或者声明您的方法可能会引发此异常。 您可以通过如下更改方法callmethodErr的签名来callmethodErr这一点:

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

有关其工作原理的更多详细信息,请参见:Oracle Java教程中的“捕获或指定要求”

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM