Is it a bad practice to catch a RuntimeException for logging purposes?

I came across the fact that catching a RuntimeException is usually considered bad practice because they cannot be fixed and are usually programmer errors.

However, we have a (insanely) large application in which changes in any part can have unforeseen consequences (yes, this problem in itself).

Now there is an idea to start catching and registering RuntimeExceptions at the top level of the application, so that we can be more effective in eliminating such bleeding problems that arise.

Like any good Java team, we have a wonderful, zealous follower of Uncle Bob, who absolutely forbids us from doing this.

How bad is it to do? Are there really cases when this is normal or even recommended?

+4
source share
4 answers

It’s not always bad to catch RuntimeException. But even if your team decided not to catch RuntimeException, you can always catch it, register something, and then throw it away again. It will not change your application logic at all.

Almost all log libraries now have the ability to log various exception information (such as stacktrace and all nested exceptions) in addition to the log message.

public void doStuff(String param){
  try {
    process(param);
  } catch(RuntimeException e) {
    logger.error("Something weird happened while processing " + param, e);
    throw e;
  }
}


The following is an updated context information, thanks to Ralph Kleberhoff for pointing this out

RuntimeException ( Exception) , .

(, , Ralf Kleberhoff), catch ( , catch ), Exception Exception cause .

public void doStuff(String param){
  try {
    process(param);
  } catch(RuntimeException e) {
    throw new RuntimeException("Something weird happened while processing " + param, e);
  }
}

private void process(String value){
  throw new IllegalStateException("Not implemented yet!");
}
+4

RuntimeExceptions , , . Java , RuntimeExceptions, RuntimeError.

, RuntimeExceptions, , . RuntimeExceptions / , . , , .

, . - i.E. , .

+5

, RuntimeException .

This can be useful when using third-party code that throws its own exceptions, extending RuntimeException, and then you need to catch it in order to do good exception handling.

Also in JSP It is sometimes useful to catch RuntimeExceptionin order to prevent the page from appearing at all because of NullPointerException.

0
source

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


All Articles