How to create custom exception in java

 

What is custom exceptionin java?

In simple terms, a custom exception in Java is an exception that you create yourself to handle specific error conditions in your code. It allows you to define and throw exceptions that are tailored to your application's needs.

Java provides a set of built-in exception classes, such as Exception, RuntimeException, and their subclasses. However, sometimes these general exceptions may not fully capture the exceptional scenarios specific to your application. In such cases, you can create your own custom exception by extending one of the existing exception classes or creating a new one from scratch.



Advantages of using custom exceptions in Java:

·       Improved code readability: By creating custom exceptions, you can give meaningful names to specific exceptional situations in your code. This makes your code more readable and self-explanatory, as it clearly communicates the nature of the exception being thrown.

·       Enhanced error handling: Custom exceptions allow you to handle exceptional cases differently based on their types. You can catch and handle specific custom exceptions separately, providing more targeted error handling and recovery mechanisms.

·       Better maintainability: By encapsulating specific exceptional scenarios within custom exceptions, you can separate the error-handling logic from the main code, leading to more maintainable and modular code. It becomes easier to identify and handle different types of exceptions in a centralized manner.

·       Customized error messages: Custom exceptions enable you to provide custom error messages that convey relevant information about the exceptional condition. This helps in troubleshooting and debugging the code, as the error messages can provide specific details about the cause of the exception.


Here's a small example to illustrate the use of a custom exception:


public class InvalidInputException extends Exception {

    public InvalidInputException(String message) {

        super(message);

    }

}


public class Calculator {

    public int divide(int dividend, int divisor) throws InvalidInputException {

        if (divisor == 0) {

            throw new InvalidInputException("Divisor cannot be zero.");

        }

        return dividend / divisor;

    }

}


public class Main {

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        try {

            int result = calculator.divide(10, 0);

            System.out.println("Result: " + result);

        } catch (InvalidInputException e) {

            System.out.println("Invalid input: " + e.getMessage());

        }

    }

}


In this example, the Calculator class has a divide() method that divides two numbers. If the divisor is zero, it throws a custom exception called InvalidInputException. In the main() method, we catch the InvalidInputException and display a custom error message.


Now, let's consider a larger example where a custom exception is used in a file processing application:


public class FileProcessingException extends Exception {

    public FileProcessingException(String message) {

        super(message);

    }

}


public class FileProcessor {

    public void processFile(String filePath) throws FileProcessingException {

        try {

            // Read the file and perform some processing

            // If an error occurs, throw the custom exception

        } catch (IOException e) {

            throw new FileProcessingException("Error processing file: " + e.getMessage());

        }

    }

}

 

public class Main {

    public static void main(String[] args) {

        FileProcessor fileProcessor = new FileProcessor();

        try {

            fileProcessor.processFile("path/to/file.txt");

        } catch (FileProcessingException e) {

            System.out.println("File processing error: " + e.getMessage());

        }

    }

}

 

In this example, the FileProcessor class has a processFile() method that reads a file and performs some processing. If an IOException occurs during the processing, it is caught, and a custom exception called FileProcessingException is thrown. In the main() method, we catch the FileProcessingException and handle it appropriately.