While working on an application, you may come across some scenarios where you feel like the Exceptions defined in the java platform are not enough to represent the error/issue you want to tell the end user. In that case you may choose to write your own exception. That is called a User Defined or Custom Exception.
Lets see how to define User Defined Exceptions in Java.
While creating a user defined exception, your exception should always extend from Exception or any of its Subclass. Also its always good to append the string Exception to the names of all classes that inherit (directly or indirectly) from the Exception class. This will help readability.
User Defined Exception class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.kscodes.exception; public class EmployeeNotFoundException extends Exception { public EmployeeNotFoundException() { super(); } public EmployeeNotFoundException(String arg0, Throwable arg1) { super(arg0, arg1); } public EmployeeNotFoundException(String arg0) { super(arg0); } public EmployeeNotFoundException(Throwable arg0) { super(arg0); } } |
Use the Exception in your code
1 2 3 4 5 6 7 8 9 10 |
public Employee searchEmployee(String firstName) throws EmployeeNotFoundException { // Some code to search employee and if not found than throw your // exception Employee employee = employeeSearchService.findEmp(firstName); if (employee == null) { throw new EmployeeNotFoundException("Employee with FirstName " + firstName + " not found"); } return employee; } |
Handling your exception
1 2 3 4 5 6 7 |
EmployeeSearch search = new EmployeeSearch(); try { search.searchEmployee("Steve Smith"); } catch (EmployeeNotFoundException enfEx) { System.out.println(enfEx); enfEx.printStackTrace(); } |
Output
If a Exception is thrown then the Catch block will show the below in the console.
1 2 3 4 |
com.kscodes.exception.EmployeeNotFoundException: Employee with FirstName Steve Smith not found com.kscodes.exception.EmployeeNotFoundException: Employee with FirstName Steve Smith not found at com.kscodes.test.EmployeeSearch.searchEmployee(EmployeeSearch.java:23) at com.kscodes.test.EmployeeSearch.main(EmployeeSearch.java:11) |