Pages

Wednesday, December 1, 2021

Java - Creating Custom Exception

1. Overview

In this article, We'll learn how to create custom exceptions in java.

We'll show how to define user defined exceptions and how can be used as both checked and unchecked custom exceptions with examples.

First, we will understand the use of custom exceptions and then how to implement custom checked, unchecked exceptions.

Java - Creating Custom Exception




2. Understand the need for custom exceptions


Java comes with a set of predefined exceptions that cover all or common scenarios.

But, we need to define some of the standard exceptions on our own.

There are mainly 2 reasons to write our own custom exceptions.

2.1 Business logic exceptions - Exceptions unique to the business logic and its process.

These are very useful to the application developers in determining the actual nature of the problem.

2.2 To identify and offer particular treatment or execution flow for a subset of the Java exceptions.






3. Java - Custom Checked Exceptions


Checked exceptions are one type of exception and there has to be handled by the code explicitly. These can not be ignored by the developers additionally will get the compile time errors.


Let us create a simple scenario where we need to use the custom checked exceptions.

When you are reading the contents from the file and then you need to handle FileNotFoundException manually. Because if the file does not exist or provided path does not exist.

Example 1

package com.javaprogramto.exception.custom.checked;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CustomCheckedException {

	public static void main(String[] args) {

		String fileName = "hello.txt";
		String firstLine;

		try (Scanner file = new Scanner(new File(fileName))) {
			if (file.hasNextLine())
				firstLine = file.nextLine();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

	}
}

Output
hello.txt (No such file or directory)
java.io.FileNotFoundException: hello.txt (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:212)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154)
	at java.base/java.util.Scanner.<init>(Scanner.java:639)
	at com.javaprogramto.exception.custom.checked.CustomCheckedException.main(CustomCheckedException.java:14)


We are getting the FileNotFoundException. The actual reason might be folder is not present or the file is not present. Now to get the specific error, you need to write a custom exception implementation to throw the user defined exception for the InvalidFileNamePatternException and FoldersNotFoundException.

Let us create the custom checked exception

For the user defined checked custom exception class must extend Exception class as below.

Exception 2

package com.javaprogramto.exception.custom.checked;

public class InvalidFileNamePatternException extends Exception {

	public InvalidFileNamePatternException(String reason) {
		super(reason);
	}

}

How to use and throw custom checked exceptions?

When this exception scenario is met then you need to use the throw keyword to throw this custom exception.

Example 3

package com.javaprogramto.exception.custom.checked;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CustomCheckedException {

	public static void main(String[] args) throws InvalidFileNamePatternException {

		String fileName = "hello.txt";
		String firstLine;

		try (Scanner file = new Scanner(new File(fileName))) {
			if (file.hasNextLine())
				firstLine = file.nextLine();
		} catch (FileNotFoundException e) {
			if (!isValidFileName(e.getMessage())) {
				throw new InvalidFileNamePatternException("Expected file name is banks.txt but found " + fileName);
			}
		}

	}

	private static boolean isValidFileName(String msg) {

		if (msg.contains("bank.txt")) {
			return true;
		}

		return false;
	}

}

Output

Exception in thread "main" com.javaprogramto.exception.custom.checked.InvalidFileNamePatternException: Expected file name is banks.txt but found hello.txt
	at com.javaprogramto.exception.custom.checked.CustomCheckedException.main(CustomCheckedException.java:19)

Now, we could see the new user custom exception rather than built-in common exception.

Here, we are throwing our custom exception, but if you want you can send the actual error to the custom exception as below with Throwable as an argument.

Custom checked with the actual error

Example 4

package com.javaprogramto.exception.custom.checked;

public class InvalidFileNamePatternException extends Exception {

	public InvalidFileNamePatternException(String reason, Throwable t) {
		super(reason, t);
	}

}

Verifying new custom exception error message

Example 5

		try (Scanner file = new Scanner(new File(fileName))) {
			if (file.hasNextLine())
				firstLine = file.nextLine();
		} catch (FileNotFoundException e) {
			if (!isValidFileName(e.getMessage())) {
				throw new InvalidFileNamePatternException("Expected file name is banks.txt but found " + fileName, e);
			}
		}



Output

Now you can see the custom error and the old underlying error from the file not found exception.

Exception in thread "main" com.javaprogramto.exception.custom.checked.InvalidFileNamePatternException: Expected file name is banks.txt but found hello.txt
	at com.javaprogramto.exception.custom.checked.CustomCheckedException.main(CustomCheckedException.java:19)
Caused by: java.io.FileNotFoundException: hello.txt (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:212)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154)
	at java.base/java.util.Scanner.<init>(Scanner.java:639)
	at com.javaprogramto.exception.custom.checked.CustomCheckedException.main(CustomCheckedException.java:14)

Like this, you can add another custom checked exception for the FoldersNotFoundException if the file name pattern is correct and the folder is not present.


4. Java - Custom UnChecked Exceptions


To create the unchecked exception, we need to extend java.lang.RuntimeExceptin class.

Custom unchecked exceptions need not be handled explicitly at the compile because these things only be detected at the runtime only.

Creating runtime custom unchecked exception

Exception
package com.javaprogramto.exception.custom.checked;

public class InvalidFileNamePatternException2 extends RuntimeException {

	public InvalidFileNamePatternException2(String reason, Throwable t) {
		super(reason, t);
	}

}


How to throw a custom unchecked exception?

package com.javaprogramto.exception.custom.checked;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CustomUnCheckedException {

	public static void main(String[] args) {

		String fileName = "hello.txt";
		String firstLine;

		try (Scanner file = new Scanner(new File(fileName))) {
			if (file.hasNextLine())
				firstLine = file.nextLine();
		} catch (FileNotFoundException e) {
			if (!isValidFileName(e.getMessage())) {
				throw new InvalidFileNamePatternException2("Expected file name is banks.txt but found " + fileName, e);
			}
		}

	}

	private static boolean isValidFileName(String msg) {

		if (msg.contains("bank.txt")) {
			return true;
		}

		return false;
	}

}


Output

Exception in thread "main" com.javaprogramto.exception.custom.checked.InvalidFileNamePatternException2: Expected file name is banks.txt but found hello.txt
	at com.javaprogramto.exception.custom.checked.CustomUnCheckedException.main(CustomUnCheckedException.java:19)
Caused by: java.io.FileNotFoundException: hello.txt (No such file or directory)
	at java.base/java.io.FileInputStream.open0(Native Method)
	at java.base/java.io.FileInputStream.open(FileInputStream.java:212)
	at java.base/java.io.FileInputStream.<init>(FileInputStream.java:154)
	at java.base/java.util.Scanner.<init>(Scanner.java:639)
	at com.javaprogramto.exception.custom.checked.CustomUnCheckedException.main(CustomUnCheckedException.java:14)






5. Java - Create Custom Exceptions - More Examples


Let us create a few more custom exception examples for better understanding.

This example for the real-time example of a custom exception. process() method throws the custom checked exception and stop() method throws the unchecked exception.

Example

package com.javaprogramto.exception.custom.checked;

import java.util.Random;

public class CustomExceptionExample1 {

	public static void main(String[] args) throws CustomException {

		Process p = new WordProcess();
		boolean isProcessed = p.process();

		if (isProcessed) {
			p.stop();
		}

	}

}

class CustomException extends Exception {

	public CustomException(String reason) {

		super(reason);
	}
}

class CustomUncheckedException extends RuntimeException {

	public CustomUncheckedException(String reason) {

		super(reason);
	}
}

interface Process {

	boolean process() throws CustomException;

	boolean stop();
}

class WordProcess implements Process {

	@Override
	public boolean process() throws CustomException {

		if (new Random().nextInt(10) % 2 == 0) {
			throw new CustomException("Expecte odd number - but received even no ");
		}

		return false;
	}

	@Override
	public boolean stop() {

		if (new Random().nextInt(10) % 2 != 0) {
			throw new CustomUncheckedException("Expecte odd number - but received even no ");
		}

		return false;
	}
}

 
Output of checked exception

Exception in thread "main" com.javaprogramto.exception.custom.checked.CustomException: Expecte odd number - but received even no 
	at com.javaprogramto.exception.custom.checked.WordProcess.process(CustomExceptionExample1.java:49)
	at com.javaprogramto.exception.custom.checked.CustomExceptionExample1.main(CustomExceptionExample1.java:10)


Output of unchecked exception

Exception in thread "main" com.javaprogramto.exception.custom.checked.CustomUncheckedException: Expecte odd number - but received even no 
	at com.javaprogramto.exception.custom.checked.WordProcess.stop(CustomExceptionExample1.java:60)
	at com.javaprogramto.exception.custom.checked.CustomExceptionExample1.main(CustomExceptionExample1.java:10)


6. When to use custom checked and unchecked exceptions


6.1 Checked Exceptions


It is recommended to use the checked exceptions for the file related processings and which are mandated for processings. And also prefer when you prepare the dependency jars for another team, go for the checked exceptions.

What do you expect to be present for the processing at the compile-time handled properly?

6.2 Unchecked Exception


These are occurred at the runtime and are heavily used for validations. When the money is getting transferred to another account then sent should account should have a sufficient balance. If the amount is less than the requested amount then need to throw the custom unchecked exception as InsufficientBalanceException.



7 Conclusoon


in this article, we've seen how to create the custom exceptions and when to use custom checked and unchecked exceptions.




No comments:

Post a Comment

Please do not add any spam links in the comments section.