This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

Can I catch multiple Java exceptions in the same catch clause?

In Java, I want to do something like this:

try {
    ...     
} catch (/* code to catch IllegalArgumentException, SecurityException, 
            IllegalAccessException, and NoSuchFieldException at the same time */) {
   someCode();
}
Copy the code

. Instead of:

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

Is there any way?

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

In Java 7, you can define multiple catch clauses, such as:

catch (IllegalArgumentException | SecurityException e)
{
    ...
}
Copy the code

Answer:

If an exception hierarchy exists, you can use the base class to catch all subclasses of the exception. In the case of degeneracy, you can catch all Java exceptions with the following command:

try {
   ...
} catch (Exception e) {
   someCode();
}
Copy the code

More commonly, if RepositoryException is the base class and PathNotFoundException is a derived class, then:

try {
   ...
} catch (RepositoryException re) {
   someCode();
} catch (Exception e) {
   someCode();
}
Copy the code

The code above captures RepositoryException and PathNotFoundException for one kind of exception handling and combines all the other exceptions together. Starting with Java 7, follow @oscarryz’s answer above:

try { 
  ...
} catch( IOException | SQLException ex ) { 
  ...
}
Copy the code

The article translated from kgs4h5t57thfb6iyuz6dqtun5y ac4c6men2g7xr2a – stackoverflow – com. Translate. Goog/questions / 3…

For example, we can use sections to catch exceptions globally, but we can also catch exceptions within a specified block of code


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️