Spring Exception Handling Tutorial
Join the DZone community and get the full member experience.
Join For Freeyou 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
|
Opinions expressed by DZone contributors are their own.
Comments