Java Custom Exception refers to the creation of user-defined exception classes in Java. There are times when developers must define their own unique exceptions to handle particular application-specific errors or exceptional conditions, even though Java comes with a set of built-in exceptions to handle common error scenarios.
Creating a custom exception involves creating a new class that extends one of the existing exception classes provided by Java, such as Exception or RuntimeException. By defining custom exceptions, developers can provide more meaningful and specific information about the exceptional condition, making it easier to handle and debug errors within their applications.
By creating custom exceptions, developers can define their own set of application-specific error conditions and handle them accordingly. This helps in writing more expressive and organized code, making it easier to identify and resolve issues.
A subset of current Java exceptions to be caught and given a particular treatment.
Exceptions relating to business logic and workflow are referred to as this. Understanding the precise issue is helpful for both app users and developers.
We must extend the Exception class from the java.lang package in order to produce a unique exception.
User Define Exception
class UserDefineException extends Exception {
public UserDefineException(String s){
super(s); // calling parent Exception
}
}
publicclass Main { // class to use user define above exceptionpublicstaticvoid main(String args[]){
try {
thrownew UserDefineException("DockerTpoint");
}
catch (UserDefineException ex) {
System.out.println("Catch Block");
System.out.println(ex.getMessage());
}
}
}
Output:
Catch Block
DockerTpoint
The call to super is not required when using the constructor of the Exception class, which can also be used without a parameter.
Example : User Define Exception
class UserDefineException extends Exception { }
publicclass Main { // class to use user define above exceptionpublicstaticvoid main(String args[]){
try {
thrownew UserDefineException(); // Throw a user-defined exception object
}
catch (UserDefineException ex) {
System.out.println("Catch Block");
System.out.println(ex.getMessage());
}
}
}
Post your comment