Is there a better way to catch only a specific reason (s) for an exception?

Given this stack:

java.lang.RuntimeException: ... Caused by: com.mypackage.SpecificException 

And this try-catch:

 try { ts.init(); } catch (RuntimeException e) { if (e.getCause() instanceof SpecificException) { //do something } else { throw e; } } 

I cannot change the code for a SpecificException , nor the method that wraps this exception in a RuntimeException .

Is there a better way to catch only a SpecificException ?

+6
source share
1 answer

The only Java mechanism is to choose which exceptions for catch are specific exception classes. If you want to distinguish the exceptions of the same class depending on their causes, then you should catch all the exceptions of this class, as you demonstrate.

Note, however, that it is problematic to throw the exception as soon as you catch it, because it replaces the original stack trace with a new, context-specific new throw . This can make debugging a lot more difficult. To avoid this, you will need to wrap the exception of the individual new exception caught as the reason and throw it away.

+5
source

Source: https://habr.com/ru/post/984238/


All Articles