简体   繁体   English

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

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

I am trying to compile this code, but it keeps having an error, 我正在尝试编译此代码,但它始终出现错误,

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

This exception is thrown in the callmethodErr() , and I thought it has been caught in main, but I can't figure out what is happening. 这个异常抛出在callmethodErr() ,我认为它已经被main捕获了,但是我不知道发生了什么。

Thanks all. 谢谢大家

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

This method: 该方法:

public static void callmethodErr()
{

Contains the line: 包含以下行:

throw new Exception();          

But does not declare that it throws Exception thus: 但不声明因此throws Exception

public static void callmethodErr() throws Exception
{

Exception is a checked exception, and that means you must catch it in the method in which it is thrown, or declare that your method might throw this exception. Exception是一个已检查的异常,这意味着您必须在引发该异常的方法中捕获它,或者声明您的方法可能会引发此异常。 You can do that by changing the signature of your method callmethodErr like this: 您可以通过如下更改方法callmethodErr的签名来callmethodErr这一点:

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

For a more details description of how this works, see: The Catch or Specify Requirement in Oracle's Java Tutorials. 有关其工作原理的更多详细信息,请参见:Oracle Java教程中的“捕获或指定要求”

As the compiler says, the method callmethodErr can throw an Exception. 正如编译器所说,方法callmethodErr可以引发Exception。 So you must catch that Exception in the method callmethodErr or declare the method callmethodErr to throw the Exception. 因此,您必须在方法callmethodErr捕获该Exception或声明该方法callmethodErr引发该异常。 Whether you catch it in the main method or not is not relevant, because you could also call the method callmethodErr from another method (not the main) and forget about catching it, and the compiler must prevent this. 是否在main方法中捕获它callmethodErr ,因为您还可以从另一个方法(不是main)中调用方法callmethodErr ,而忘记捕获它,因此编译器必须防止这种情况。

Declare the method like this public static void callmethodErr() throws Exception 声明像这样的方法public static void callmethodErr() throws Exception

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

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