How to create Java Custom Exception?

How to create Java Custom Exception?

Java provides a huge hierarchy of Exceptions include both checked and unchecked exceptions. But sometimes when we have to choose which type of exception to be thrown, we can either choose the one already defined by Java or we can write our own custom Java exception.

But when will you require to write your exception, or I would say, how to decide when to write a custom Exception?

The main reasons for introducing custom exceptions are:

  • Business logic exceptions: Exceptions that are specific to the business logic and workflow. These help the application users or the developers understand what the exact problem is.
  • To catch and provide specific handling to an exception to provide clear exception cause.

We can write both checked and unchecked custom exception, let’s see how to create it.

Checked custom exception:

For example, refer following code snippet.

public static void readFromFile()  {
    try {
        File file = new File("/home/inputfile.txt");
        InputStream is = new FileInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        System.out.println(br.readLine());
        
        is.close();
        br.close();
        
    } catch (IOException e) {   
        e.printStackTrace();
    }

}

In the above code snippet, the IOException can be caused by multiple reasons. i.e. FileNotFoundException. Even FileNotFoundException can have multiple causes, like the file is not available or the file is present but the file name is not valid. So what if we want to tell the user that the file name is not valid. In this case, we can make our Custom checked exception and throw it if the name is not valid.

Let’s create the custom checked exception.

public class InvalidFileNameException extends Exception{
    
    private static final long serialVersionUID = 3411057007944826395L;

    public InvalidFileNameException(String message) {
        super(message);
    }
}

Now, let’s rewrite the above method using custom exceptions. Observe the following code snippet.

public class CustomExceptionExample{
    
    public static void main(String[] args) throws InvalidFileNameException {
        readFromFile();
    }

    public static void readFromFile() throws InvalidFileNameException  {
        File file = null;
        try {
            file = new File("/home/input.file.txt");
            InputStream is = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            System.out.println(br.readLine());
            
            is.close();
            br.close();
            
        } catch (IOException e) { // this IOException can be caused by multiple reason. i.e. FileNotFoundException  
            if(e instanceof FileNotFoundException) {
                if(isInvalidFileName(file.getName())) {
                    throw new InvalidFileNameException("file name "+file.getName() + " is not valid");
                }
            }
        }
    }
    
    // Invalid file name if it has multiple dot (.)
    static boolean isInvalidFileName(String fileName) {
        String [] arr = fileName.split("\\.");
        return arr.length > 2;
    }    
}

Using this way we can tell the user that, the file name is not valid.

Unchecked custom exception:

Similar to the checked custom exception, we can create an unchecked custom exception. Assume we are reading text from a text file, but if the input is not a text file we should throw an exception that the file extension is not valid. Observe the below code, we will come to know about the file extension only during the runtime, hence we will create an unchecked custom exception to throw invalid file extension.

Let’s create a custom unchecked exception.

public class InvalidFileExtension extends RuntimeException {

    private static final long serialVersionUID = -7284958373872448993L;
    
    public InvalidFileExtension(String message) {
        super(message);
    }
}

Observe the following code snippet.

public class CustomExceptionExample{
    
    public static void main(String[] args) throws InvalidFileNameException {
        readFromFile();
    }

    public static void readFromFile() throws InvalidFileNameException  {
        //file = new File("/home/input.file.txt");
        File file = new File("/home/abc.gif");
        
        try (Scanner sc = new Scanner(file)){
            
            if(sc.hasNextLine()) {
                System.out.println(sc.nextLine());
            }else {
                throw new InvalidFileExtension("not a valid file " + file.getName());
            }    
        }catch (FileNotFoundException e) {
            if(isInvalidFileName(file.getName())) {
                throw new InvalidFileNameException("file name "+file.getName() + " is not valid");
            }
        }
    }
    
    // Invalid file name if it has multiple (.)
    static boolean isInvalidFileName(String fileName) {
        String [] arr = fileName.split("\\.");
        return arr.length > 2;
    }    
}

If the custom exception is implemented properly, it can be very helpful for writing business logic and effective application logging.

Recommended read:
Exception in detail
How to create custom Java Exception?

Happy Learning !!

Reference:

Exception Oracle Docs

Leave a Comment