In this lesson, you will learn
Exception class or one of its subclasses, making them part of Java’s normal exception-handling mechanism.

It follows the 2 steps process
You can create user-defined exceptions by extending the Throwable class or any of its subclasses.
The following example creates a new class MyCustomException that is the subclass of Exception and then uses that subclass to signal an error condition in a method.
It overrides the toString( ) method, allowing a carefully tailored description of the exception to be displayed.
//This program creates a custom exception type.
class MyCustomException extends Exception {
private int detail;
public MyCustomException(int a) {
detail = a;
}
@Override
public String toString() {
return "MyCustomException [detail=" + detail + "]";
}
}
Here we define a subclass of Exception called MyCustomException. This subclass is quite simple: It has only a constructor plus an overridden toString( ) method that displays the value of the exception.
public class CustomExceptionMain {
public static void process(int a) throws MyCustomException {
System.out.println("Called process(" + a + ")");
if(a > 10) {
throw new MyCustomException(a);
}
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
process(1);
process(15);
} catch (MyCustomException e) {
System.out.println("Caught: "+e);
}
}
}
The CustomExceptionMain class defines a method named process( ) that throws a MyCustomException object. The exception is thrown when process( )‘s integer parameter is greater than 10.
The main( ) method sets up an exception handler for MyCustomException and then calls process( ) with a legal value (less than 10) and an illegal one. Here is the result.
Called process(1)
Normal exit
Called process(15)
Caught: MyCustomException [detail=15]
Imagine an application that requires a user to input data within a certain range, and you want to handle invalid inputs with a custom exception.
package exceptionhanding;
class InvalidInputException extends Exception {
public InvalidInputException() {
System.out.println("Invalid Input: ");
}
public InvalidInputException(String message) {
super(message);
}
}
public class InputValidator {
public static void validate(int input) throws InvalidInputException {
if (input < 1 || input > 100) {
throw new InvalidInputException("Input must be between 1 and 100.");
}
System.out.println("Valid input: " + input);
}
public static void main(String[] args) {
try {
validate(45);
validate(150);
} catch (InvalidInputException e) {
System.err.println(e.getMessage());
}
}
}
Output
Valid input: 45
Input must be between 1 and 100.
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.