• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to create Custom Exception in Java

April 8, 2019 by javainterviewpoint Leave a Comment

Java allows us to create our own exception class and throw the created exception using throw keyword. These exceptions are known as the Custom Exception or User-Defined Exception. In this article, we will learn how to create Custom Exception in Java, including both Custom Checked Exception and Custom UnChecked Exception.

Why we need Custom Exceptions?

Java has a lot of built exceptions such as IOException, NullPointerException, etc, but these exceptions will not always be the best fit for the business requirements. We will mostly need the custom exception for the business needs rather than technical issues.

For example, IOException can be thrown when a particular file is not present and NullPointerException can be thrown when a particular entity is null but these exceptions cannot be used in a scenario where you are validating a user and we might need to throw an InvalidUserException rather than a predefined exception.

Custom Exception

Custom Checked Exception / Custom Compile time Exception

Let’s create a Custom Checked Exception, which will be thrown whenever an invalid user name is keyed in. In order to create a custom compile time exception all you have to do is to extend Exception class.

package com.javainterviewpoint;

public class InvalidUserException extends Exception
{
	public InvalidUserException(String message)
	{
		super(message);
	}
}

The Custom exception (InvalidUserException) class has a constructor that takes a string error message as a parameter and in turn calls the parent class constructor using the super keyword.

So why do we need to call the base class constructor using super?

Can’t we ignore this call?

It is necessary to initialize the base class as the first step before construction of the derived class object. If no explicit call is made then Java will call the default no parameter constructor of the Exception class and the message/cause will be missed. Therefore, it is good practice to use the super keyword to call the parameterized constructor of the base class and initialize it with the error message.

Now let’s see how to throw our custom compile time exception in our UserValidator class.

package com.javainterviewpoint;

import java.util.Scanner;

public class UserValidator
{
	public static void main(String[] args) throws InvalidUserException
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the username to validate :");
		String userName = scanner.nextLine();
		
		if(userName.equals("JIP"))
			System.out.println("Valid username entered");
		else
			throw new InvalidUserException("Invalid username entered");
	}
}

In the above code we are validating the username entered, if the username entered is equal to “JIP” then we are simply printing the message “Valid username entered”, else we are throwing InvalidUserException with the message “Invalid username entered”

Note: Since the checked exception follows handle or declare rule, we have declared our custom checked exception using the throws keyword at the method signature.

Output:

Enter the username to validate :
Java
Exception in thread "main" com.javainterviewpoint.InvalidUserException: Invalid username entered
	at com.javainterviewpoint.UserValidator.main(UserValidator.java:16)

Custom UnChecked Exception / Custom Runtime Exception

The above way of creating user-defined exception works fine but it will force us to either handle the exception using try catch or declare the user-defined exception using throws keyword.

In order to overcome the above said issues, we can create custom unchecked exception, all you have to do is to extend RuntimeException class.

package com.javainterviewpoint;

public class InvalidAgeException extends RuntimeException
{

	public InvalidAgeException(String message)
	{
		super(message);
	}
	
}
package com.javainterviewpoint;

import java.util.Scanner;

public class AgeValidator
{
	public static void main(String[] args) throws InvalidUserException
	{
		Scanner scanner = new Scanner(System.in);
		System.out.println("Enter the Age to validate :");
		int age = scanner.nextInt();
		
		if(age > 1 && age < 150)
			System.out.println("Valid Age entered");
		else
			throw new InvalidAgeException("Invalid Age entered");
	}
}

In the above code we are just validating the age entered, if the age entered is greater than 1 and less than 150 then we are simply printing the message “Valid Age entered”, else we are throwing InvalidAgeException with the message “Invalid Age entered”

Output:

Enter the Age to validate :
255
Exception in thread "main" com.javainterviewpoint.InvalidAgeException: Invalid Age entered
	at com.javainterviewpoint.AgeValidator.main(AgeValidator.java:16)

Note: we did not use the throws keyword at the message signature to declare our custom exception since it is an unchecked exception. The client who is calling our AgeValidator class will have to use a try catch to handle the exception when occurred.

Preserving the Exception stack and Re-throwing using Custom Exception

It is a common practice to catch the built-in Java exception and throw the user-defined exception with additional information which can be error status codes or custom error message etc. We need to be sure that we are not losing any stack trace which will help us to debug.

All we need to do is create a custom exception either checked or unchecked exception with a constructor which takes the error message and cause as a parameter.

package com.javainterviewpoint;

public class InvalidUserException extends Exception
{
    public InvalidUserException(String message, Throwable cause)
    {
        super(message, cause);
    }
    public InvalidUserException(String message)
    {
        super(message);
    }
}

package com.javainterviewpoint;

import java.util.Scanner;

public class UserValidator
{
    public static void main(String[] args) throws InvalidUserException
    {
        try
        {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter the username to validate :");
            String userName = scanner.nextLine();

            if (userName.equals("JIP"))
                System.out.println("Valid username entered");
            else

                throw new Exception();
        } catch (Exception e)
        {
            throw new InvalidUserException("Invalid username entered", e);
        }
    }
}

In the InvalidUserException class, we have added a new constructor with two parameters one for holding the error message and other holding the cause (Throwable) and both the parameters are passed to the base class using super()

Output:

Enter the username to validate :
Java
Exception in thread "main" com.javainterviewpoint.InvalidUserException: Invalid username entered
	at com.javainterviewpoint.UserValidator.main(UserValidator.java:22)
Caused by: java.lang.Exception
	at com.javainterviewpoint.UserValidator.main(UserValidator.java:19)

Other interesting articles which you may like …

  • Exception Handling in Java
  • RSA Encryption and Decryption
  • Java URL Encode and Decode Example
  • Java Salted Password Hashing
  • Google Tink Example – Google Cryptography
  • AES 256 Encryption and Decryption
  • AES 128 Encryption and Decryption
  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java Tagged With: Custom Checked Exception, Custom Compile time Exception, Custom Exception, Custom Runtime Exception, Custom UnChecked Exception, User-Defined Exception

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·