This post demonstrate , how to write you own custom exception in java here I have made UserNotFoundException
. By naming convention, this Exception throws when user not found for provided userId. Here there are three class first, UserNotFoundException.java
(custom exception) , second DAO ( UserDAOImpl.java
) and third class Client application which run and gives the output of program. for simlicity throws explicitly.
Write Custom Exception
Write your custome exception , e.g. UserNotFoundException
which basically used to throw when user by id not found.
UserNotFoundException.java
package com.mysoftkey.exception;
/**
* @author ranjeet.jha
*
*/
public class UserNotFoundException extends Exception {
/**
* @param throwable
*/
public UserNotFoundException(Throwable throwable) {
super(throwable);
}
public UserNotFoundException( String msg, Throwable throwable) {
super(msg, throwable);
}
public UserNotFoundException( String msg) {
super(msg);
}
}
DAO (Data Access Object )
From DAO (Data Access Object ) we should throw exception if user not found by userId. Here, I throws explicitly just to demonstrate how to throws UserNotFoundException
, it means just to demonstrate how to throws custom exception.
UserDAOImpl.java
package com.mysoftkey.exception;
import java.util.HashMap;
import java.util.Map;
/**
* @author ranjeet@mysoftkey.com
*
*/
public class UserDAOImpl {
/**
* @param id
* @return
* @throws Exception
* @throws UserNotFoundException
*/
public Map getUserById(int id) throws Exception, UserNotFoundException {
Map userMap = new HashMap();
try {
// here explicitly throwing exception.
throw new UserNotFoundException("User not found for id: " + id);
} catch(UserNotFoundException e) {
throw e;
} catch (Exception e) {
}
return userMap;
}
}
Client Class (UserManager.)
UserManager.java
package com.mysoftkey.exception;
import java.util.Map;
/**
* @author ranjeet
*
*/
public class UserManager {
/**
* @param args
*/
public static void main(String[] args) {
UserDAOImpl dao = new UserDAOImpl();
try {
System.out.println("befor calling to pull user by id.");
Map userMap = dao.getUserById(10);
System.out.println(userMap.toString());
System.out.println("After calling to pull user by id.");
} catch (Exception e) {
// here we get same message which I set while throwing of UserNotFoundException
System.err.println("messg: "+ e.getMessage());
e.printStackTrace();
}
}
}
Output of Program
messg: User not found for id: 10
befor calling to pull user by id.
com.mysoftkey.exception.UserNotFoundException: User not found for id: 10
at com.mysoftkey.exception.UserDAOImpl.getUserById(UserDAOImpl.java:28)
at com.mysoftkey.exception.UserManager.main(UserManager.java:21)
Write you comments or suggestion to improve this post.