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:
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
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! ❤ ️ ❤ ️ ❤ ️ ❤ ️