0

I have a class with a method that throws some exceptions and catches them inside itself, but when i call it in my Main class they seem to not being catched.

An example about my problem:

public class Test { public static void method (int number) throws InvalidNumberException { try { if (number == 5) { throw new InvalidNumberException("Invalid number"); } } catch (InvalidNumberException inv) { System.out.println(inv); } } } public class InvalidNumberException extends Exception { public InvalidNumberException (String s) { super(s); } } public class Main { public static void main(String args[]) { Test.method(5); } } 

When i try to compilate the last one i get this error:

Main.java:3: error: unreported exception InvalidNumberException; must be caught or declared to be thrown Test.method(5);

Is there a way to fix it without catching the exception in the Main class?

1 Answer 1

1

Because you're catching the InvalidNumberException inside of method, there's no need for a throws clause, however, the existence of it mandates that calls to it must handle the exception. Thus, the compiler is expecting you to handle the exception in main.

To solve this, simply remove the throws clause modifying method, since you're already handling the exception inside.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.