Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Creating and Understanding Custom/User-defined Exceptions in Java

 

In this lesson, you will learn

  • What is Custom or User-Defined Exceptions in Java
  • Creating User-Defined Exception
  • Examples

 

What is User-defined or Custom Exceptions in Java

  • Although Java’s built-in exceptions handle the most common errors, you can create your own exceptions (custom or user-defined) also based on the specific application need.
  • By defining custom exceptions, you can provide more detailed and context-specific error information to the users of your application.
  • You can create user-defined exceptions by extending either the Exception class or one of its subclasses, making them part of Java’s normal exception-handling mechanism.

 

 

How to Create User-Defined Exception

It follows the 2 steps process

  1. Creating a User-Defined Exception Class
  2. Implementing User-Defined Class as Part of Normal Exception Handling Mechanism

 

1. Creating a User-Defined Exception Class

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.

 

2. Implementing User-Defined Class as Part of Normal Exception Handling Mechanism

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]

 

Example 2: InvalidInputException

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.

 

 

 

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

 

 

There are no reviews yet. Be the first one to write one.

 

 

Submit a Review