Can you handle multiple exceptions in the same catch statement when handling exceptions?

Asked 2 years ago, Updated 2 years ago, 128 views

When we make an exception in Java.

try {
    ...     
} } catch (IllegalArgumentException e) {
    someCode();
} } catch (SecurityException e) {
    someCode();
} } catch (IllegalAccessException e) {
    someCode();
} } catch (NoSuchFieldException e) {
    someCode();
}

Normally, we make exceptions like the code above. But for me

try {
    ...     
} } catch (IllegalArgumentException, SecurityException, 
       IllegalAccessException, NoSuchFieldException e) {
   someCode();
}

I want to make an exception at once like this. Is there any way?

java exception try-catch

2022-09-22 22:30

1 Answers

It's possible from Java 7. In the try-catch phrase

try { 
  ...
} } catch( IOException | SQLException ex ) { 
  ...
}

You can do it like this. Remember, not before Java 7. This is possible if all exceptions belong to the same class, but in different cases, you need to create a catch phrase.


2022-09-22 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.