user3411919
user3411919

Reputation: 33

Catching exception types twice

Can we catch an exception type twice in the main method with different messages? I want to print out a different warning.

Ex:

 try {
    // some code
 } catch (NumberFormatException e) {
    System.out.println("Wrong input!"); 
 } catch (NumberFormatException e) {
    System.out.println("No valid number!"); 
 }

Upvotes: 0

Views: 2577

Answers (4)

Rakesh KR
Rakesh KR

Reputation: 6527

You can´t catch the same exception twice.

Consider the following example,

try {

} catch (FileNotFoundException e) {
    System.err.println("FileNotFoundException: " + e.getMessage());
    throw new SampleException(e);

} catch (IOException e) {
    System.err.println("Caught IOException: " + e.getMessage());
}

Here,

Both handlers print an error message. The second handler does nothing else. By catching any IOException that's not caught by the first handler, it allows the program to continue executing.

The first handler, in addition to printing a message, throws a user-defined exception.

Upvotes: 0

As i understand your comments you want to display the right message for your exception:

 try {
    // some code
 } catch (NumberFormatException e) {
    System.out.println(e.getMessage()); 
 }

Upvotes: 0

Guillermo Merino
Guillermo Merino

Reputation: 3257

You can´t catch the same exception twice.

What you can do is to throw a custom exception in your code and catch it if you want a different behaviour.

try{
   ...
   throw new YourException(yourMessage);
}catch(YourException e){

}

Upvotes: 0

peter.petrov
peter.petrov

Reputation: 39437

You cannot catch the same exception type (like NumberFormatException) twice. I suggest you catch it once but in the catch block, you print two messages instead.

Upvotes: 3

Related Questions