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).
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.
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.
Since Exception is the base class of all exceptions, it will catch any exception.
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 .
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); }
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With