Spring Database Exceptions

Exceptions are common in any java based application, exceptions will follow a hierarchy before breaking the compiler. In spring there is a parent class to handle all types of exceptions which is called DataAccessException. We can handle all types of exception using this class. If you want to handle specific exception with some child class there are many child exception classes for every breaking operation. Lets have an example.

lets take code from previous example.

What happen in the below code is we defined a parent exception “DataAccessException” which handles every exception type. we also catched “CannotGetJdbcConnectionException” which only catches the exception if the connection details are wrong. We should follow the exception hierarchy give by spring to catch any exception correctly.

App.java


package com.caveofprogramming.spring.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;

public class App {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext(
"com/sourceforopensource/beans/beans.xml");

OffersDAO offersDao = (OffersDAO) context.getBean("offersDao");

try {
List<Offer> offers = offersDao.getOffers();

for (Offer offer : offers) {
System.out.println(offer);
}
}
catch(CannotGetJdbcConnectionException ex) {
System.out.println("Cannot get database connection.");
}
catch (DataAccessException ex) {
System.out.println(ex.getMessage());
System.out.println(ex.getClass());
}

((ClassPathXmlApplicationContext) context).close();
}

}

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

Leave a Reply

Your email address will not be published. Required fields are marked *