-4

Is it a bad practice to catch Throwable?For example my code something like this.But in sonar its showing as bug .How can we resolve this

code

try {
            return restTemplate.getForObject(urlSearchID, AccessIDSearchResponse.class);

        } catch (HttpServerErrorException hse) {
            AccesIdExceptionUtility.recoverFromHttpServerExc(hse);
        } catch (HttpClientErrorException hce) {
            AccesIdExceptionUtility.recoverFromHttpClientExc(hce);
        } catch (ClientException ce) {
            AccesIdExceptionUtility.recoverFromClientExc(ce);
        } catch (Exception e) {
            AccesIdExceptionUtility.recoverFromException(e);
        }
        catch (Throwable ex) {
            throw new ServiceException(ErrorMessages.EPO_SYSTEM_ERROR, ex.getMessage(), agentSearchUrl);
        }
        return null;
Krish
  • 4,166
  • 11
  • 58
  • 110
  • 3
    Does this answer your question? [Is it a bad practice to catch Throwable?](https://stackoverflow.com/questions/6083248/is-it-a-bad-practice-to-catch-throwable) – akuzminykh Jun 01 '20 at 11:52
  • I am understanding those answers can you please paste your answer here – Krish Jun 01 '20 at 11:57

2 Answers2

0

Yes, as a general rule, it's a bad idea.

You are catching Errors as well as Exceptions. You almost certainly are not handling them correctly. For example, you're mishandling ThreadDeath according to my reading of the documentation. And your chances of doing anything useful on VirtualMachineError are slim to none.

Since recovery is unlikely, the effect is that you'll obfuscate the original problem, making your debugging life harder.

user13463803
  • 281
  • 2
  • 4
0

Yes it's a bad practise. In Java Throwable is a base class for Error and Exception. You are already familiar with Exceptions, they can be checked or unchecked, so you can catch them and handle, log or rethrow.

Errors are more complicated, they are JVM eroror like OutOfMemoryException which is a VirtualMachineError. How are you gonna handle this in your code? Answer is: you simply can't.

If you google for "Recoverable and Irrecoverable Situations" Exceptions are Recoverable Situations, because you can handle NullPointerException and Irrecoverable Situations are Errors.

If you want check Baeldung, it's really good blog about Java, Spring etc. https://www.baeldung.com/java-catch-throwable-bad-practice

Piotr Solarski
  • 316
  • 2
  • 6