1
\$\begingroup\$

My existing code has a scheduler that we init when a DataStore constructor is called.

private void initSchedulers() {
    int initialDelay = applicationStartupConfig.getSchedulerInitialDelay();
    int refreshPeriod = applicationStartupConfig.getSchedulerRefreshPeriod();
    // above are fetched using config.yml(dropwizard)

    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            try {
                initializeCache(); // some operation that we perform to fetch data on to the cache on a scheduled basis
            } catch (Throwable t) {
                logger.error("Scheduler could not complete : ", t);
            }

        }
    }, initialDelay, refreshPeriod);
}

Evaluating the code under Sonar Analysis reports this as Vulnerable --

Throwable is the superclass of all errors and exceptions in Java.

Error is the superclass of all errors, which are not meant to be caught by applications.

Catching either Throwable or Error will also catch OutOfMemoryError and InternalError, from which an application should not attempt to recover.

Though I understand the above statements yet I am not able to draw a conclusion on

  1. What if I catch Exception today, and a runtime error exception is thrown later? Would that not stop the scheduler?
  2. Is there a way to specify handling both these cases and ensuring that this does not create impact on client calls to the DataStore?
\$\endgroup\$

2 Answers 2

3
\$\begingroup\$

That is exactly what Sonar says: "... from which an application should not attempt to recover".

Thus, if you catch Exception and NOT Error, yes, this will effectively terminate your scheduler and probably impact the DataStore. BUT: as Errors indicate a severity, where the VM probably won't be working reliably anyway (also see https://docs.oracle.com/javase/8/docs/api/java/lang/Error.html) this is exactly the thing to do: terminate the program, bail out, call the admin. When you continue working under error conditions, the result is generally somewhat undefined. Better avoid this.

\$\endgroup\$
1
\$\begingroup\$

To answer your question,

Please define "runtime error exception". If you mean by runtime exception, it would be logged in your catch block. RuntimeException is subclass of Exception class. If you mean by runtime error, your application really can't do much. See the link from the previous answer.

Catching "Throwable" is misleading because it looks like handling the Error in Java but actually not. That is what Sonar is warning for.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.