문제

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