Meyyappan has posted 101 posts at DZone. View Full User Profile

Spring Exception Handling Tutorial

06.15.2012
| 28215 views |
  • submit to reddit

You need not handle any database-related exceptions explicitly instead Spring JDBC Framework will handle it for you. All the exceptions thrown by the Spring JDBC Framework are subclasses of DataAccessException which is a type of RuntimeException, so you need not handle it explicitly. Any checked exception when thrown will be mapped to any of the subclasses of the DataAccessException by the framework.

package com.vaannila.dao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.dao.EmptyResultDataAccessException;

import com.vaannila.domain.Forum;

public class Main {

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				"beans.xml");
		ForumDAO forumDAO = (ForumDAO) context.getBean("forumDAO");
		Forum springForum = new Forum(1, "Spring Forum",
				"Discuss everything related to Spring");
		try {
			forumDAO.insertForum(springForum);
		} catch (DuplicateKeyException e) {
			System.out.println("Forum Already Exist");
		} catch (DataAccessException e) {
			e.printStackTrace();
		}
		try {
			System.out.println(forumDAO.selectForum(2));
		} catch (EmptyResultDataAccessException e) {
			System.out.println("The Forum id is invalid");
		} catch (DataAccessException e) {
			e.printStackTrace();
		}

	}

}

Don't handle any exceptions in the DAO layer, instead throw it to the front-end and handle it. To handle the exception all you need to do is to catch the appropriate exception in the hierarchy and address it. When you run this example for the first time a Forum will be created, when you run it again you will get a DuplicateKeyException, which we catch it in the catch block and display the appropriate message. Only one Forum exist in the database with the forum id '1', if you query for the forum with forum id '2' then you will get the "The Forum id is invalid" message dispalyed on the console.

The class hierarchy of the DuplicateKeyException is shown below.

You can download and try the example here.

Source :Download
Source + Lib :Download

 

Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: