The Java Specialists wrote a post about Exceptions in Java, and in it they list a few "best practices" for creating Exceptions, summarized below:

  • Don't Write Own Exceptions (there are lots of useful Exceptions that are already part of the Java API)

  • Write Useful Exceptions (if you have to write your own Exceptions, make sure they provide useful information about the problem that occurred)

Answer from Josh Brown on Stack Overflow
Top answer
1 of 8
23

The Java Specialists wrote a post about Exceptions in Java, and in it they list a few "best practices" for creating Exceptions, summarized below:

  • Don't Write Own Exceptions (there are lots of useful Exceptions that are already part of the Java API)

  • Write Useful Exceptions (if you have to write your own Exceptions, make sure they provide useful information about the problem that occurred)

2 of 8
16

Don't do what the developers at my company did. Somebody created an [sic] InvalidArguementException that parallels java.lang.IllegalArgumentException, and we now use it in (literally) hundreds of classes. Both indicate that a method has been passed an illegal or inappropriate argument. Talk about a waste...

Joshua Bloch covers this in Effective Java Programming Language Guide [my bible of first resort on Best Practices] Chapter 8. Exceptions Item 42: Favor the use of standard exceptions. Here's a bit of what he says,

Reusing preexisting exceptions has several benefits. Chief among these, it makes your API easier to learn and use because it matches established conventions with which programmers are already familiar [my emphasis, not Bloch's]. A close second is that programs using your API are easier to read because they aren't cluttered with unfamiliar exceptions. Finally, fewer exception classes mean a smaller memory footprint and less time spent loading classes.

The most commonly reused exception is IllegalArgumentException. This is generally the exception to throw when the caller passes in an argument whose value is inappropriate. For example, this would be the exception to throw if the caller passed a negative number in a parameter representing the number of times some action were to be repeated.

That said, you should never throw Exception itself. Java has a well-chosen, diverse and well-targeted bunch of built-in exceptions that cover most situations AND describe the exception that occurred well enough so that you can remedy the cause.

Be friendly to the programmers who have to maintain your code in the future.

🌐
Baeldung
baeldung.com › home › java › core java › create a custom exception in java
Create a Custom Exception in Java | Baeldung
May 11, 2024 - 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. Learn the basics of exception handling in Java as well as some best and worst practices.
🌐
Stackify
stackify.com › java-custom-exceptions
Implement Custom Exceptions in Java: Why, When and How
May 1, 2023 - Learn 4 best practices for custom exceptions in Java. Understand when and how to use them in your application.
🌐
DEV Community
dev.to › saurabhkurve › best-practices-and-pitfalls-in-java-exception-handling-37dk
Best Practices and Pitfalls in Java Exception Handling ✨ - DEV Community
December 13, 2024 - Best Practice: Wrap the core logic in a single try-catch block where appropriate, or refactor to streamline exception handling. Handling exceptions in Java requires thoughtful design and attention to detail.
🌐
Medium
medium.com › @nweligalla › creating-custom-exceptions-in-java-ea77a61fcaf4
Creating Custom Exceptions in Java | by Nayana Weligalla | Medium
January 31, 2024 - To make your own exception in Java, you typically need to create a custom class that extends the Exception class or one of its subclasses, such as RuntimeException. Before you create any exceptions, it’s a good idea to follow some best practices for creating specially naming your custom ...
🌐
How to do in Java
howtodoinjava.com › home › exception handling › effective approach for creating custom exceptions in java
Effective Approach for Creating Custom Exceptions in Java
April 7, 2023 - We have been using handling java custom exceptions in our code for almost every industry standard application. Usual approach is to create some custom exception classes extending the base Exception class. These classes are generally mapped to ...
🌐
DZone
dzone.com › data engineering › databases › implementing custom exceptions in java
Implementing Custom Exceptions in Java
November 13, 2017 - Learn why and how to create and code custom exceptions in Java, how to properly document them and link to those docs, and general best practices for their use.
🌐
GeeksforGeeks
geeksforgeeks.org › java › user-defined-custom-exception-in-java
User-Defined Custom Exception in Java - GeeksforGeeks
Add methods to provide additional details about the exception. (this is optional) Example 1: Checked Custom Exception (Real-World Scenario)
Published   August 14, 2025
Find elsewhere
Top answer
1 of 7
16

Like many things in programming, using custom exceptions is good if done for the right reasons and in the right situations.

If a built-in exception can acurrately describe the situation at hand, use it. E.g. FileNotFoundException, TimeoutException, KeyNotFoundException, etc.

If non of the built-in exception classes describe the situation, then you should make your own. If custom exceptions were bad, the built-in classes would be sealed or final or similar. However, don't go nuts. Just like with classes, a given exception type should probably be thrown from more than one place, otherwise it is likely unnecessarily specific.

However, a better rule of the thumb for whether to have custom exceptions is to consider what the caller will do about it when the exception gets thrown. If you have three erroneous situations that are handled in three very different ways, it makes sense to have three types because then the caller can have three catch blocks accordingly. The alternative, which is to inspect the message or data to decide what to do, is more complicated and thus more prone to error.

If all three situations instead are handled identically, it may not be worth the hassle of additional types, when just using the exception message should be enough to diagnose what the situation is. I've had to deal with many situations where a function can throw a dozen different exception types, but that to me as the caller, have inconsequential differences, so laziness kicks in and I just catch {} without the exception type and feel a little guilty about it. Don't cause that to happen.

As for one of the claims you wrote:

catching exceptions is performance hurting.

While that is true, there is virtually no difference between having custom exceptions that are caught and thrown vs just using ApplicationException for everything and making decisions based on the exception message. However, the for former situation, it is considerably easier for us humans to reason about what is happening during program execution.

2 of 7
6

There's one thing I see in the existing answers that bothers me:

Catching custom exceptions might be code smell.

If you are creating custom exceptions, you shouldn't be catching them. Exceptions are for when things go horribly wrong and recovery is impossible. Exceptions that can be handled are either your own fault or vexing.

Taking from the MSDN article Vexing Exceptions:

I first classify every exception I might catch into one of four buckets which I label fatal, boneheaded, vexing and exogenous.

Fatal exceptions are not your fault, you cannot prevent them, and you cannot sensibly clean up from them.

Boneheaded exceptions are your own darn fault, you could have prevented them and therefore they are bugs in your code.

Vexing exceptions are the result of unfortunate design decisions.

And finally, exogenous exceptions appear to be somewhat like vexing exceptions except that they are not the result of unfortunate design choices. Rather, they are the result of untidy external realities impinging upon your beautiful, crisp program logic.

I recommend reading the whole post.

Any design that creates vexing exceptions is a bad design. You (and anyone else writing code against your api) has to catch them, and doing so is vexing: so avoid creating new vexing exceptions.

Custom exception types should either be exogenous ("I'm sorry, Dave, but the database went offline")--and most of these kinds of exceptions have already been written--or Fatal and you should never handle fatal exceptions.

This last point is not adequately presented in the other answers. A bad credit card number is a validation error not an exception. Errors are communicated to the user because they can fix it. Exceptions are things the user can never do anything about. Exogenous exceptions are the exception here, as they are the fault of the world at large and the user needs to be aware of them, even if they can't fix it (but sometimes they can: Internet is disabled, the disk was ejected, the information was wrong. Regardless, there is nothing you as the developer can do to fix it: catch, display, don't crash).

A FamilyNameException is boneheaded: your code had a bug in it. Do not create boneheaded exceptions, do not handle them, write your code correctly in the first place so that these do not occur. Custom exception types are inappropriate for this reason.

A LoginException is either exogenous (the database is offline) or PEBKAC. If it is a PEBKAC error, it isn't an exception. If it is exogenous, why is the existing exception type not sufficient? There may be cases where custom exception types are relevant, but be sure to communicate properly! For example I wrote some code that communicated with an external service, which took time. My coworker was trying to ask my code for the results before the request had time to return, so my code had to generate an exception. However, he took this exception (which was boneheaded in nature) and treated it like a vexing: caught the error and assumed all zeros, thereby introducing a bug: the data retrieved from the external service was wrong! (No, the data was right, but he wasn't displaying the retrieved data and blamed my code). I ended up having to fix his code twice (he removed my first fix about 2 weeks after I added it).

To sum up:

  • Catching any fatal or boneheaded exception is code smell.
  • A custom vexing exception class is code smell. See also: How to avoid vexing exceptions.
  • Be careful with custom exogenous exceptions: they are either redundant or can be mistaken for vexing exceptions.
🌐
Hero Vired
herovired.com › home › learning-hub › topics › custom-exceptions-in-java
How to Create Custom Exceptions in Java - Hero Vired
Creating custom exceptions is useful, but there are best practices to follow. Use clear, meaningful names for your exceptions. ... Include extra fields if necessary to convey more information.
🌐
Stack Abuse
stackabuse.com › how-to-make-custom-exceptions-in-java
How to Make Custom Exceptions in Java
November 10, 2019 - Let's create a custom exception to handle this situation. To create an exception, like any other exception, we have to extend the java.lang.Exception class: public class EmailNotUniqueException extends Exception { public EmailNotUniqueException(String message) { super(message); } } Note that we provided a constructor that takes a String error message and calls the parent class constructor. Now, this is not mandatory but it's a common practice to have some sort of details about the exception that occurred.
🌐
j-labs
j-labs.pl › home › tech blog › java exception handling: strategies and best practices
Java Exception Handling in Java Best Practices | j‑labs
September 10, 2024 - In this article, we have discussed essential best practices, strategies, and real-world examples that empower Java developers to master the art of exception handling, enhancing the overall quality of their software projects.
🌐
Blogger
javarevisited.blogspot.com › 2014 › 06 › how-to-create-custom-exception-in-java.html
How to create Custom Exception in Java - Tutorial Example
7) For readable code, it's good practice to append the string Exception to the names of all classes that inherits (directly or indirectly) from the Exception class e.g. instead of naming your class IncorrectPassword, name it IncorrectPasswordException. That's all about How to create custom Exception classes in Java. As I said, first try to avoid the temptation of creating a brand new Exception class, think if you can reuse existing ones. If you absolutely need, then make sure to follow best practices.
🌐
Spark Code Hub
sparkcodehub.com › java › custom-exception
Java Custom Exception: Enhancing Error Handling in Your ...
By defining checked or unchecked ... from banking systems to APIs. Adhering to best practices—such as using descriptive names, providing contextual data, and choosing the right exception type—ensures that custom exceptions add value without overcomplicating the ...
🌐
GitHub
github.com › msorkhpar › Claude-senior-java-engineer › blob › main › 12-custom-exception › README_3.2.3.md
Claude-senior-java-engineer/12-custom-exception/README_3.2.3.md at main · msorkhpar/Claude-senior-java-engineer
A3: Here are some best practices for creating and using custom exceptions: Use descriptive names that clearly indicate the error condition. Extend the appropriate base class (Exception for checked, RuntimeException for unchecked).
Author   msorkhpar
🌐
Hyperskill
hyperskill.org › learn › step › 15639
Custom exceptions
Hyperskill is an educational platform for learning programming and software development through project-based courses, that helps you secure a job in tech. Master Python, Java, Kotlin, and more with real-world coding challenges.
🌐
Cursa
cursa.app › all courses › information technology › programming languages ( python, ruby, java, c ) › learn to program in complete java, from programming logic to advanced
Java best practices and coding standards: Using custom exceptions : Course Learn to program in complete Java, from programming logic to advanced | Cursa
To create a custom exception in Java, you simply need to define a new class that extends the Exception class or any of its subclasses. If the exception you are creating is a checked exception, it must extend Exception directly.
Author   Cursa: Free Online Courses + Free Certificate
Pages   238
🌐
Reddit
reddit.com › r/java › how do you structure your exception classes?
r/java on Reddit: How do you structure your exception classes?
January 17, 2024 -

On my team, we mostly use the built-in Java exceptions with a top level try-catch that logs and alerts us.

You probably see where this is going.. we get alerted for every single exception, and many of these are not actionable by us (user errors).

We now have a filter layer that filters out alerts that match a regex, so we aren’t alerted for everything now but it’s still not ideal.

I want a way to distinguish between exceptions we need to be alerted on and exceptions that can just be warnings.

I see 2 main approaches:

  1. An AlertException class that we subclass and throw. We catch these at the top level and alert accordingly.

  2. Some sort of Alertable marker interface that we throw and do an instance of check on. One variant is the interface could also have a method like “responseType” that returns an enum with values like: Alert Oncall, Warn, Alert user

I’m leaning towards approach 2 but would love to hear your ideas! Thanks!

Top answer
1 of 22
55
Is this a Spring Web app? If so there is a built-in annotation called @ControllerAdvice. You can annotate a global exception handler class with that and you can handle custom exceptions using that. For the custom exceptions you'll want to subclass the built-in Exception class.
2 of 22
24
I would at the very least define your own exception base type so that every exception that your code throws is an instance of that type. Depending on how many systems/modules/libraries your systems consists of, perhaps you need more than one base type. If you're interested in differences in meaning between various instances of your base type exception then I recommend creating different subclasses, but I would try to make those meaningful in the sense that they should convey what sort of error they're signalling. We now have a filter layer that filters out alerts that match a regex This you should not be doing. The information you need to make these decisions should be communicated either via structured fields (enums, booleans, etc) or the exception type. An AlertException class that we subclass and throw This I would definitely not do. The whole point of exceptions is that in your code when something bad happens you can package up information about the problem and throw it up the stack so that higher-level code which knows what the context is can handle the problem. Because what the correct error handling is depends on context. If you have a class like this then basically every time you throw an exception you have to make this alert/not alert decision, but you don't want those decisions spread all over the codebase. You also don't necessarily know everywhere in the codebase whether this is alertable or not. Instead, make the code communicate what sort of error has happened, and then have the decisions at higher levels. Personally, I think it sounds odd to do alerting on individual exceptions instead of using metrics and defining alerts on those. Note that this is all generic advice, because you said nothing about what sort of application this is.
🌐
Medium
medium.com › @satyendra.jaiswal › mastering-error-handling-creating-and-utilizing-custom-exception-classes-in-java-c3834f36d5da
Mastering Error Handling: Creating and Utilizing Custom Exception Classes in Java | by Satyendra Jaiswal | Medium
January 4, 2025 - To create a custom exception class, you simply extend the Exception class or one of its subclasses. Let's start with a basic example – imagine you are developing a banking application, and you want to handle a scenario where an account balance ...