1

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.

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();      
    }
  } 
}
mortalis
  • 2,060
  • 24
  • 34
Talia
  • 21
  • 3

3 Answers3

4

This method:

public static void callmethodErr()
{

Contains the line:

throw new Exception();          

But does not declare that it throws Exception thus:

public static void callmethodErr() throws Exception
{
Stewart
  • 17,616
  • 8
  • 52
  • 80
2

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. You can do that by changing the signature of your method callmethodErr like this:

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.

Jesper
  • 202,709
  • 46
  • 318
  • 350
2

As the compiler says, the method callmethodErr can throw an Exception. So you must catch that Exception in the method callmethodErr or declare the method callmethodErr to throw the Exception. 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.

Declare the method like this public static void callmethodErr() throws Exception

RaffoSorr
  • 405
  • 1
  • 5
  • 14