Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To combine two catch clasuses in the same [duplicate]

Tags:

java

exception

I have the following code:

try {
    //do some
} catch (NumberFormatException e) {
    return DynamicFilterErrorCode.INVALID_VALUE;
} catch (ClassCastException e) {
    return DynamicFilterErrorCode.INVALID_VALUE;
} catch (IllegaleArgumentException e) {
    return DynamicFilterErrorCode.INVALID_VALUE;
}

Is it possible to combine those 3 catch clauses into one? They have exactly the same handler code, so I'd like to reuse it.

like image 352
St.Antario Avatar asked May 14 '15 10:05

St.Antario


People also ask

Can there be two catch statements?

Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception . Only one of the catch block will handle your exception. You can have try block without a catch block.

Can you have two catch statements in Java?

Multiple Catch Block in Java Starting from Java 7.0, it is possible for a single catch block to catch multiple exceptions by separating each with | (pipe symbol) in the catch block. Catching multiple exceptions in a single catch block reduces code duplication and increases efficiency.

How do you catch two exceptions in the same catch block?

If a catch block handles multiple exceptions, you can separate them using a pipe (|) and in this case, exception parameter (ex) is final, so you can't change it.

Can we have multiple catches for the same try?

Yes, we can define one try block with multiple catch blocks in Java. Every try should and must be associated with at least one catch block.


1 Answers

From Java 7 it is possible :

try {
    //do some
} catch (NumberFormatException | ClassCastException | IllegaleArgumentException e) {
    return DynamicFilterErrorCode.INVALID_VALUE;
} 
like image 80
Eran Avatar answered Oct 04 '22 22:10

Eran