Spring Exception Handling Tutorial

DZone 's Guide to

Spring Exception Handling Tutorial

· ·
Free Resource

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(
		forumdao forumdao = (forumdao) context.getbean("forumdao");
		forum springforum = new forum(1, "spring forum",
				"discuss everything related to spring");
		try {
		} catch (duplicatekeyexception e) {
			system.out.println("forum already exist");
		} catch (dataaccessexception e) {
		try {
		} catch (emptyresultdataaccessexception e) {
			system.out.println("the forum id is invalid");
		} catch (dataaccessexception e) {



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


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}