Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to catch all exceptions except runtime exceptions?

Tags:

I have a statement that throws a lot of checked exceptions. I can add all catch blocks for all of them like this:

try {     methodThrowingALotOfDifferentExceptions(); } catch(IOException ex) {     throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); } catch(ClassCastException ex) {     throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); } catch... 

I do not like this because they are all handled same way so there is kind of code duplication and also there is a lot of code to write. Instead could catch Exception:

try {     methodThrowingALotOfDifferentExceptions(); } catch(Exception ex) {     throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); } 

That would be ok, except I want all runtime exceptions to be thrown away without being caught. Is there any solution to this? I was thinking that some clever generic declaration of the type of exception to be caught might do the trick (or maybe not).

like image 614
Rasto Avatar asked Nov 14 '12 12:11

Rasto


People also ask

Do all exceptions occur at runtime?

All the exceptions occur at runtime. On the other hand, UnchekedExceptions[aka RuntimeExcetions] are less likely to occur and the programmer is not forced to handle those while writing the program.

How do you catch all exceptions except one?

Try and Except Statement – Catching all Exceptions Try and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.

Does exception catch all exceptions?

Since Exception is the base class of all exceptions, it will catch any exception.

Why runtime exceptions are not checked?

Because the Java programming language does not require methods to catch or to specify runtime exceptions or errors, programmers can be tempted to write code that throws only runtime exceptions or to make all their exception subclasses inherit from RuntimeException .


2 Answers

You could do the following:

try {     methodThrowingALotOfDifferentExceptions(); } catch(RuntimeException ex) {     throw ex; } catch(Exception ex) {     throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); } 
like image 85
bdoughan Avatar answered Feb 14 '23 23:02

bdoughan


If you can use Java 7, you can use a Multi-Catch:

try {   methodThrowingALotOfDifferentExceptions(); } catch(IOException|ClassCastException|... ex) {   throw new MyCustomInitializationException("Class Resolver could not be initialized.", ex); } 
like image 31
Urs Reupke Avatar answered Feb 14 '23 23:02

Urs Reupke