Custom Exception In Java

Custom Exception in Java: We’ve already discussed exception handling in Java in this blog, describing the differences between checked and unchecked exceptions, best practices, and common mistakes. If you’ve read these posts, you can understand the situation that caused the exception.

This article will discuss creating a custom exception in Java with examples. But we recommend the previous articles on Exception handling to get the prior knowledge.

Post Type:Core Java Tutorial For Beginners
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

Why Use Custom Exceptions?

The answer is that Java exceptions cover nearly all exceptional cases and conditions. However, it’s also possible that your application might throw a specific custom exception that is unique to your code and logic. If this happens, the JDK won’t be able to find any relevant exceptions, so you’ll need to create new ones on your own.

Using custom exceptions in Java, programmers can better understand what went wrong and where. So, the custom exception is beneficial in exception handling, specifically for APIs, because we mainly use custom logic, and based on the logic, we are getting the response codes sent to the clients.

By defining a custom exception, if it does not provide benefits, there is no need to create a custom exception, and you should use the existing JDK exceptions.

How do you create a custom exception or user-defined exception in Java?

To create a User Defined Exception or Custom exception, you can follow the below steps:

  • Create a new Java class with an Exception at the end of the file name, which helps you easily find the custom exception classes. For example: ClassNameException
  • The newly created classes should be extended to the Java.lang.Exception class.
  • You can create a constructor for your exception by adding a String parameter, which will be the detailed message of the exception. In this constructor, you would call the super constructor and pass in the message.

In Java, there are two types of exceptions:

  • Checked exceptions
  • Unchecked exceptions

Check Exceptions: We need to extend the Java.lang.Exception class for handling checked exceptions. Handle the exceptions and recover from exceptions by using try-catch statements, but if you do not handle these checked exceptions, you will get compile-time errors.

Unchecked Exceptions: Similarly checked exception, for handling the unchecked exception, you have to extend Java.lang.RuntimeException. These exceptions are used for unrecoverable conditions, so the programmer has to take responsibility for handling those exceptions.

So now we will learn how to create custom or user-defined exceptions in Java in detail with examples.

Checked Custom Exception or User Defined Exception

package com.softwaretestingo.Exception;
import java.util.ArrayList;
// Create A Checked Custom exception
class customexception1 extends Exception
{
	public customexception1(String message) 
	{
		// Call the Constructor of Exception Class
		super(message);
	}
}
public class CheckedCustomExceptionEx1 
{
	//Create an ArrayList to Store List Of Students
	ArrayList<String> student=new ArrayList<>();

	//Try to Add Students into the ArrayList
	public void addStudent(String name) throws customexception1
	{
		// If the Name is already available in the Student list then throw exception
		if(student.contains(name))
		{
			throw new customexception1(name + " Already Present in the List");
		}
		else
		{
			//Add the Name into the List
			student.add(name);
			System.out.println(name + " Added Into the Student List");
		}
	}

	public static void main(String[] args) 
	{
		CheckedCustomExceptionEx1 obj=new CheckedCustomExceptionEx1();

		//Calling Method to Add the Student
		/* During adding the Student there is chance of Exception 
		so we are using try catch statements*/
		try 
		{
		obj.addStudent("Harish");
		obj.addStudent("Sonali");
		obj.addStudent("Bala");
		obj.addStudent("Harish");
		}
		catch (customexception1 e)
		{
			System.out.println("[" + e + "] Exception Occured");
		}
	}
}

Output:

Harish Added Into the Student List
Sonali Added Into the Student List
Bala Added Into the Student List
[com.softwaretestingo.Exception.customexception1: Harish Already Present in the List] Exception Occured

In the example above, we extended the Exception class to create a custom exception named customexception1. Here, we call the constructor of the Exception class from the customexception1 class using the super() keyword.

If an exception occurs inside the addStudent() method, we have checked the condition, and the try..catch block will handle it.

Above, we have seen how to create checked exceptions, and now we will see how to create unchecked user-defined or unchecked custom exceptions.

Unchecked Custom Exception or User-Defined Exception

package com.softwaretestingo.Exception;
import java.util.ArrayList;
// Create A Unchecked Custom exception
class customexception2 extends RuntimeException
{
	public customexception2(String message) 
	{
		// Call the Constructor of RuntimeException Class
		super(message);
	}
}
public class UncheckedCustomExceptionEx2 
{
	//Create an ArrayList to Store List Of Students
	ArrayList<String> student=new ArrayList<>();

	//Try to Add Students into the ArrayList
	public void addStudent(String name) throws customexception2
	{
		// If the Name is already available in the Student list then throw exception
		if(student.contains(name))
		{
			throw new customexception2(name + " Already Present in the List");
		}
		else
		{
			//Add the Name into the List
			student.add(name);
			System.out.println(name + " Added Into the Student List");
		}
	}

	public static void main(String[] args) 
	{
		UncheckedCustomExceptionEx2 obj=new UncheckedCustomExceptionEx2();

		//Calling Method to Add the Student
		/* During adding the Student there is chance of Exception 
		so we are using try catch statements*/
		obj.addStudent("Harish");
		obj.addStudent("Sonali");
		obj.addStudent("Bala");
		obj.addStudent("Harish");
	}
}

Output:

Harish Added Into the Student List
Sonali Added Into the Student List
Bala Added Into the Student List
Exception in thread "main" com.softwaretestingo.Exception.customexception2: Harish Already Present in the List
	at com.softwaretestingo.Exception.UncheckedCustomExceptionEx2.addStudent(UncheckedCustomExceptionEx2.java:23)
	at com.softwaretestingo.Exception.UncheckedCustomExceptionEx2.main(UncheckedCustomExceptionEx2.java:43)

In the above example, we have extended the RuntimeException class to create an unchecked custom exception class. This means that it will be checked at runtime. You can notice that we haven’t declared any try…catch block. However, this is not a problem because the unchecked exception is checked at runtime.

Conclusion:

If you find yourself in a situation where you need to use custom exceptions, don’t hesitate! They can be extremely helpful when used correctly. Just remember to keep them specific to your business logic and requirements.

For this reason, we have discussed User-defined custom exceptions or Custom exceptions in detail. You can reach us in the comment section if you find difficulties anywhere.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

2 thoughts on “Custom Exception In Java”

Leave a Comment