Last Updated: 06 March, 2023
An exception is an unexpected event that occurs during program execution and affects the current flow of the program execution, which can cause the program to terminate abnormally.
Java provides many built-in exception classes but also allows us to create our own exception class, which is known as a Custom Exception or User-defined Exception in Java. The Custom Exception class is basically a subclass of the built-in class Exception, and it throws that exception using the "throw" keyword.
A Java custom exception is used to customize the exception according to the needs of the user.
Syntax of Custom Exception
Although Java's built-in exceptions cover almost all of the general types of exceptions that may occur in a Java program, there are times when we need to customise the exception according to the requirement.
There are the following reasons to use custom exceptions:
To create a custom exception, we will create an exception class that extends java.lang.Exception class.
Consider the example given below, where we created a custom exception named InvalidRollNumberException.
Output
ERROR: Please pass valid roll number.
Student record is available.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com