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!"); 
 }
有帮助吗?

解决方案 2

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

其他提示

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.

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){

}

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top