Customized Exception
In this tutorial, we are going to discuss Customized Exception in Java. Based on our programming requirement, sometimes we have to create our exceptions, which are nothing but “Customized Exception.”
E.g
TooYoungException.
TooOldException.
InSufficiantFundsTransfer.
public class TooYoungException extends RuntimeException {
TooYoungException(String s) {
super(s);
}
}
public class TooOldException extends RuntimeException {
TooOldException(String s) {
super(s);
}
}
public class CustomExceptionDemo {
public static void main(String arg[]) {
int age = Integer.parseInt(arg[0]);
if(age > 60) {
throw new TooOldException("Younger age is already over");
} else if(age < 18)
throw new TooYoungException("Please wait same more time");
}
System.out.println("Thanks for register");
}
}
Note
It is recommended to define customized exceptions as unchecked. i.e., our custom exceptions class should extends RuntimeException either directly or indirectly.
In Java, you can create custom exceptions by extending the built-in Exception
class or one of its subclasses. This allows you to define exception types specific to your application’s needs. Here’s how you can create a custom exception class:
public class CustomException extends Exception {
public CustomException() {
super();
}
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable cause) {
super(message, cause);
}
public CustomException(Throwable cause) {
super(cause);
}
}
In this example, CustomException
is a custom exception class that extends the Exception
class. It provides several constructors to allow for different ways of initializing the exception object.
You can throw this custom exception in your code wherever appropriate. For example:
public class Example {
public void someMethod() throws CustomException {
// Some logic that might throw the custom exception
if (/* condition */) {
throw new CustomException("Something went wrong.");
}
}
}
And you can catch this custom exception in other parts of your code:
public class Main {
public static void main(String[] args) {
Example example = new Example();
try {
example.someMethod();
} catch (CustomException e) {
// Handle the custom exception
System.out.println("Custom exception caught: " + e.getMessage());
}
}
}
Creating custom exceptions allows you to add more meaning and context to your error handling, making your code easier to understand and maintain. It’s especially useful when you want to differentiate between different types of errors in your application.
That’s all about the Customized Exception in java. If you have any queries or feedback, please write us at contact@waytoeasylearn.com. Enjoy learning, Enjoy Java.!!