- Effective Approach for Creating Custom Exceptions in Java
- Create a Custom Exception in Java
- Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
- > CHECK OUT THE COURSE
- 1. Overview
- Further reading:
- Exception Handling in Java
- Checked and Unchecked Exceptions in Java
- Common Java Exceptions
- 2. The Need for Custom Exceptions
- 3. Custom Checked Exception
- 4. Custom Unchecked Exception
- 5. Conclusion
- Creating custom exceptions in java
Effective Approach for Creating Custom Exceptions in Java
We have been using handling Java custom exceptions in our code for almost every industry standard application. The usual approach is to create some custom exception classes extending the base exception handling best practice which might make more sense.
Suppose we are creating a custom exception DBException for representing the exceptions that occurred during the database-related operations. Traditionally, we create a DBException class by extending Exception class.
public class DBException extends Exception < public DBException() < super(); >public DBException(String message) < super(message); >public DBException(String message, Throwable cause) < super(message, cause); >>
Now, every time we are caught in a situation where there is a need to throw a database-related exception, we usually create an instance of DBException , put some information in form of a message and throw it.
Now, let’s consider there are following situations we have identified in which we need to throw DBException :
- SQL execution error
- No data exist where we expect at least one row
- Multiple rows exist where we expect only a single row
- Invalid parameters error
- and many more such cases
The problem with the above approach is that in catch block or in application code where these exceptions shall be handled, DBException does not provide enough information to handle each above-listed usecases, uniquely.
2. New Approach using Inner Classes
Our new approach uses static inner classes for every new exceptional scenario.
2.1. Create New Exception Types
Let’s solve the above problem with inner classes where we will create one class per use-case, and then group them inside DBException class.
Let us start with BaseException class which is created as an abstract and will be the superclass of all our exception classes.
public abstract class BaseException extends Exception < private String message; public BaseException(String msg) < super(msg); this.message = msg; >public String getMessage() < return message; >>
Now it is time to create out new Exception inner classes.
public class DBException < //SQL execution error public static class BadExecution extends BaseException < public BadExecution(String msg) < super(msg); >> //No data exist where we expect at least one row public static class NoData extends BaseException < public NoData(String msg) < super(msg); >> //Multiple rows exist where we expect only single row public static class MoreData extends BaseException < public MoreData(String msg) < super(msg); >> //Invalid parameters error public static class InvalidParam extends BaseException < public InvalidParam(String msg) < super(msg); >> >
Here, we created an inner class for each possible error scenario identified in starting. There can be many more extras. It depends on you only to identify and add more classes.
2.2. How to use custom exceptions?
Now to understand its usefulness, let’s create an exception and throw it. Then we will see the error message in the logs.
public class TestExceptions < public static void main(String[] args) < try < throw new DBExeption.NoData("No row found for id : x"); >catch(Exception e) < e.printStackTrace(); >> >
com.exception.DBExeption$NoData: No row found for id : x at com.test.TestExceptions.main(TestExceptions.java:7)
As you can see the log message in the exception stack trace has become more informative. It clearly tells what the error is. In the application code as well, you can check the instance of custom exception and handle it accordingly.
- The foremost advantage is that if the developer has written some doubtful message text, then also he can clearly observe what was actually wrong.
- You can use instance-of comparison in different situations where you handle different exceptional scenarios.
- You don’t need to send a single exception for a large set of exceptional conditions.
- It is easy to write unit test cases for negative cases where you know the exact exception class, you should expect.
- Logging is more meaningful and informative.
I hope this post about Java custom exceptions has been some information for you. If you have some suggestions, please write to me.
Create a Custom Exception in Java
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:
> CHECK OUT THE COURSE
1. Overview
In this tutorial, we’ll cover how to create a custom exception in Java.
We’ll show how user-defined exceptions are implemented and used for both checked and unchecked exceptions.
Further reading:
Exception Handling in Java
Checked and Unchecked Exceptions in Java
Common Java Exceptions
2. The Need for Custom Exceptions
Java exceptions cover almost all general exceptions that are bound to happen in programming.
However, we sometimes need to supplement these standard exceptions with our own.
These are the main reasons for introducing custom exceptions:
- 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 treatment to a subset of existing Java exceptions
Java exceptions can be checked and unchecked. In the next sections, we’ll cover both of these cases.
3. Custom Checked Exception
Checked exceptions are exceptions that need to be treated explicitly.
Let’s consider a piece of code that returns the first line of the file:
try (Scanner file = new Scanner(new File(fileName))) < if (file.hasNextLine()) return file.nextLine(); >catch(FileNotFoundException e) < // Logging, etc >
The code above is a classic way of handling Java checked exceptions. While the code throws FileNotFoundException, it’s not clear what the exact cause is — whether the file doesn’t exist or the file name is invalid.
To create a custom exception, we have to extend the java.lang.Exception class.
Let’s see an example of this by creating a custom checked exception called IncorrectFileNameException:
public class IncorrectFileNameException extends Exception < public IncorrectFileNameException(String errorMessage) < super(errorMessage); >>
Note that we also have to provide a constructor that takes a String as the error message and called the parent class constructor.
This is all we need to do to define a custom exception.
Next, let’s see how we can use the custom exception in our example:
try (Scanner file = new Scanner(new File(fileName))) < if (file.hasNextLine()) return file.nextLine(); >catch (FileNotFoundException e) < if (!isCorrectFileName(fileName)) < throw new IncorrectFileNameException("Incorrect filename : " + fileName ); >//. >
We’ve created and used a custom exception, so the user can now know what the exact exception is.
Is this enough? We are consequently losing the root cause of the exception.
To fix this, we can also add a java.lang.Throwable parameter to the constructor. This way, we can pass the root exception to the method call:
public IncorrectFileNameException(String errorMessage, Throwable err)
Now the IncorrectFileNameException is used along with the root cause of the exception:
try (Scanner file = new Scanner(new File(fileName))) < if (file.hasNextLine()) < return file.nextLine(); >> catch (FileNotFoundException err) < if (!isCorrectFileName(fileName)) < throw new IncorrectFileNameException( "Incorrect filename : " + fileName , err); >// . >
This is how we can use custom exceptions without losing the root cause from which they occurred.
4. Custom Unchecked Exception
In our same example, let’s assume that we need a custom exception if the file name doesn’t contain any extension.
In this case, we’ll need a custom unchecked exception similar to the previous one, as this error will only be detected during runtime.
To create a custom unchecked exception, we need to extend the java.lang.RuntimeException class:
public class IncorrectFileExtensionException extends RuntimeException < public IncorrectFileExtensionException(String errorMessage, Throwable err) < super(errorMessage, err); >>
This way, we can use this custom unchecked exception in our example:
try (Scanner file = new Scanner(new File(fileName))) < if (file.hasNextLine()) < return file.nextLine(); >else < throw new IllegalArgumentException("Non readable file"); >> catch (FileNotFoundException err) < if (!isCorrectFileName(fileName)) < throw new IncorrectFileNameException( "Incorrect filename : " + fileName , err); >//. > catch(IllegalArgumentException err) < if(!containsExtension(fileName)) < throw new IncorrectFileExtensionException( "Filename does not contain extension : " + fileName, err); >//. >
5. Conclusion
Custom exceptions are very useful when we need to handle specific exceptions related to the business logic. When used properly, they can serve as a practical tool for better exception handling and logging.
The code for the examples used in this article is available over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Creating custom exceptions in java
- Introduction to Java
- The complete History of Java Programming Language
- C++ vs Java vs Python
- How to Download and Install Java for 64 bit machine?
- Setting up the environment in Java
- How to Download and Install Eclipse on Windows?
- JDK in Java
- How JVM Works – JVM Architecture?
- Differences between JDK, JRE and JVM
- Just In Time Compiler
- Difference between JIT and JVM in Java
- Difference between Byte Code and Machine Code
- How is Java platform independent?
- Decision Making in Java (if, if-else, switch, break, continue, jump)
- Java if statement with Examples
- Java if-else
- Java if-else-if ladder with Examples
- Loops in Java
- For Loop in Java
- Java while loop with Examples
- Java do-while loop with Examples
- For-each loop in Java
- Continue Statement in Java
- Break statement in Java
- Usage of Break keyword in Java
- return keyword in Java
- Object Oriented Programming (OOPs) Concept in Java
- Why Java is not a purely Object-Oriented Language?
- Classes and Objects in Java
- Naming Conventions in Java
- Java Methods
- Access Modifiers in Java
- Java Constructors
- Four Main Object Oriented Programming Concepts of Java
- Inheritance in Java
- Abstraction in Java
- Encapsulation in Java
- Polymorphism in Java
- Interfaces in Java
- ‘this’ reference in Java