1

We are monitoring our application by using timers. In case of an exception, we would like to catch the exception, stop the timer with an error, and rethrow the same exception without handling it. Which of the following catch objects would be the best approach to handle it?

  1. Catch specific exceptions - will monitor only the specific exceptions but not all of them. Considered as best practice, but we will have to think and add all the possibilities each time we use a timer.

  2. Catch Exception - will monitor all the Exceptions but not the Errors like OOM. Considered as bad practice, but in this case, we throwing back the exception, so we won't lose any data.

  3. Catch Throwable - will monitor bot Exception and Error. Considered as bad practice, but in this case, we throwing back the exception, so we won't lose any data and we are not handling the Error.

public void run() {
  Timer timer = monitoring.timer();
  try {
    timer.start();
    // some logic
    timer.stop(aSuccessTag());
  
  // 1. catch specific exceptions 
  } catch (RuntimeException | IOException e) {
    timer.stop(new TagList().tags(aFailureTag(e.getClass())));
    throw e;
  }

  // 2. catch exception
  } catch (Exception e) {
    timer.stop(new TagList().tags(aFailureTag(e.getClass())));
    throw e;
  }

  // 3. catch error and exception
  catch (Throwable e) {
    timer.stop(new TagList().tags(aFailureTag(e.getClass())));
    throw e;
  }
}

Thanks

Elad

Elad Cohen
  • 79
  • 9
  • If you rethrow anyway, catch Throwable. Of course on OOM, for example, it is hard to know whether dealing with the timer still works or just triggers the next OOM. – Harald Feb 01 '22 at 21:15

0 Answers0