User defined custom Runtime/Unchecked exception example

What is user defined or custom exception in java?

  • User defined exceptions is concrete class extending exceptions like Exception, RuntimeException etc.
  • Create an unchecked exception by extending RuntimeException class in java
  • In our application, sometimes we would like to pass custom information to exception.
  • User defined exceptions are used to handle application specific inputs.
    • e.g. If we unable to find any user from database, we would like to pass input user id, while throwing exception. (refer UserNotFoundException in trailing code)..
  • We will take an example to create unchecked or custom exception.

Program – create user defined or custom runtime exception.

1.) UserNotFoundException Class (Custom exception class) 

  • Create a custom runtime exception class extending RuntimeExcception class.
  • UserNotFoundException is unchecked exception.
  • We have overloaded different constructors to demonstrate custom exception class.
package org.learn.exception;

public class UserNotFoundException extends RuntimeException {
 private static final long serialVersionUID = 13216733298798717L;
 private final String userId;

 public UserNotFoundException(String message, String userId) {
  super(message);
  this.userId = userId;
 }

 public UserNotFoundException(String message, Throwable error, String userId) {
  super(message, error);
  this.userId = userId;
 }

 public UserNotFoundException(Throwable e, String userId) {
  super(e);
  this.userId = userId;
 }

 public String getUserId() {
  return userId;
 }
}

2.) UserDao Class (throwing UserNotFoundException if user does not exists): 

  • UserDao class simulating database operations.
  • We have created the hashmap simulate database, to store user objects.
  • We will perform some CRUD operations with UserDao class.
  • If we unable to find user in database, we will throw UserNotFoundException.
package org.learn.dao;

import org.learn.exception.UserNotFoundException;
import org.learn.model.User;

import java.util.HashMap;
import java.util.Map;

public class UserDao {

 @SuppressWarnings("serial")
 private Map<String, User> databaseUser = new HashMap<String, User>() {
  {
   put("1", new User("1", "Angelina", 35, "Cambodia", "Female"));
   put("2", new User("2", "Brad", 46, "Shawnee", "Male"));
   put("3", new User("3", " Jennifer", 41, "LA", "Female"));
   put("4", new User("4", "Justin", 38, " Washington", "Male"));
   put("5", new User("5", "Marcel ", 42, "Cambodia", "Male"));
  }
 };

 public User getUserById(String id) {
  if (!isUserExists(id)) {
   throw new UserNotFoundException("User does not exists in database", id);
  }
  return databaseUser.get(id);
 }

 public User update(String id, User user) {
  if (!isUserExists(id)) {
   throw new UserNotFoundException("Update failed, User does not exist", id);
  }
  return databaseUser.put(id, user);
 }

 public User delete(String id) {
  if (!isUserExists(id)) {
   throw new UserNotFoundException("User does not exists in database", id);
  }
  return databaseUser.remove(id);
 }

 private boolean isUserExists(String id) {
  return databaseUser.containsKey(id);
 }
}

3.) User Class: 

  • User class representing the POJO of user.
package org.learn.model;

public class User {
    
 private String id;
    private String name;
    private int age;
    private String city;
    private String gender;

    public User() {
     
    }
    public User(String id, String name, int age, String city, String gender) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.city = city;
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", city='" + city + '\'' +
                ", gender='" + gender + '\'' +
                '}';
    }
    
    public String getId() {
  return id;
 } 
}

4.) UserService Class (catching exceptions thrown by Dao): 

  • UserService class act as client of UserDao class, we are performing db operations in UserService class.
  • We are catching the UserNotFoundException in-case user does not exist in database.
package org.learn.client;

import org.learn.dao.UserDao;
import org.learn.exception.UserNotFoundException;
import org.learn.model.User;

public class UserService {
 public static void main(String[] args) {
  UserDao userDao = new UserDao();
  String id = "1";
  // Get user by id 1
  User user = userDao.getUserById(id);
  System.out.printf("1. Got user with id %s is :%s\n", id, user);

  System.out.printf("2. Delete user with id %s\n", id);
  user = userDao.delete(id);

  // Get user by id 1, which does not exist
  try {
   user = userDao.getUserById(id);
   System.out.printf("3. Got user with id %s is :%s", id, user);
  } catch (UserNotFoundException e) {
   System.out.printf("3. Unable to get user, userId=%s, message:%s\n", e.getUserId(), e.getMessage());
  }

  // delete user by id 10, which does not exist
  id = "20";
  try {
   user = userDao.delete(id);
   System.out.printf("4. deleted user with id %s is :%s", id, user);
  } catch (UserNotFoundException e) {
   System.out.printf("4. Unable to delete user, userId=%s, message:%s\n", e.getUserId(), e.getMessage());
  }

  // delete user by id 10, which does not exist
  id = "1";
  try {
   user = userDao.update(id, null);
   System.out.printf("5. update user with id %s is :%s", id, user);
  } catch (UserNotFoundException e) {
   System.out.printf("5. Unable to update user, userId=%s, message:%s\n", e.getUserId(), e.getMessage());
  }
 }
}

Output: custom or user defined runtime exception

1. Got user with id 1 is :User{name='Angelina', age=35, city='Cambodia', gender='Female'}
2. Delete user with id 1
3. Unable to get user, userId=1, message:User does not exists in database
4. Unable to delete user, userId=20, message:User does not exists in database
5. Unable to update user, userId=1, message:Update failed, User does not exist

Download code – User defined/custom runtime exception class

 

Scroll to Top