$show=/label

Java - Creating Custom Exception

SHARE:

A quick guide to creating the custom exceptions in java. Examples on checked and unchecked custom exception types.

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.




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java - Creating Custom Exception
Java - Creating Custom Exception
A quick guide to creating the custom exceptions in java. Examples on checked and unchecked custom exception types.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicOGF7MxZz0kpFtiKpNH6646JnXqwqcTy3JfiIgVM66KILkIvddHyEJjiuRJoyB8FxevGWl-4RnNi5lnpxU9e0vKuBlpsK3ITdf67I5hIbLw_yNMBgjkwjhdxM5WDoLn7w7S4nzJpObDk/w640-h390/Java+-+Creating+Custom+Exception.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicOGF7MxZz0kpFtiKpNH6646JnXqwqcTy3JfiIgVM66KILkIvddHyEJjiuRJoyB8FxevGWl-4RnNi5lnpxU9e0vKuBlpsK3ITdf67I5hIbLw_yNMBgjkwjhdxM5WDoLn7w7S4nzJpObDk/s72-w640-c-h390/Java+-+Creating+Custom+Exception.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/12/java-custom-exception.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/12/java-custom-exception.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content