Mansur
Mansur

Reputation: 1829

All the exceptions that can be thrown by JdbcTemplate.execute() method

How can I find out which exceptions can be thrown by JdbcTemplate.execute() method call. I know it throws DataAccessException. But since DataAccessException is the parent class of actual exceptions that are thrown, that becomes a very broad statement.

For example, it throws BadSqlGrammarException which is the subclass. I know I can find it in source code, but I'd like to know if there's a list or some way to find it, plus inferring from the source code may cause problems. The reason is to catch exceptions so that I can log them and notify the user appropriately. So, how can I find out which exceptions are thrown, exactly? Should I do that or catching DataAccessException and logging its message is enough?

Upvotes: 1

Views: 1030

Answers (1)

TechFree
TechFree

Reputation: 2964

You can catch the parent exception and use raw code or one of the utility libraries to get to the exception root cause. Raw code sample below, invoked from catch block. Root cause of the exception and message should always be logged. Generally have a common exception handler centralized, to log exceptions only in one place ( example in Spring applications, we use @ControllerAdvice

private static Throwable findSpecificCause(Throwable throwable) {
        Throwable rootCause = getRootCause(throwable);
        return (rootCause != null ? rootCause : throwable);
    }

private static Throwable getRootCause(Throwable throwable) {
        if (throwable == null) {
            return null;
        }
        Throwable rootCause = null;
        Throwable cause = throwable.getCause();
        while (cause != null && cause != rootCause) {
            rootCause = cause;
            cause = cause.getCause();
        }
        return rootCause;
    }

You can also consider using libraries like Apache's common lang ExceptionUtils, Spring NestedExceptionUtils or from Guava

Also see link :Exception Root Cause

Upvotes: 1

Related Questions