You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

Usage:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}
Answer from Rion Williams on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › user-defined-custom-exception-in-java
User-Defined Custom Exception in Java - GeeksforGeeks
There are two types of custom exceptions in Java. Checked Exceptions: It extends the Exception class. and it must be declared in the throws clause of the method signature.
Published   August 14, 2025
🌐
Reddit
reddit.com › r/javahelp › help with throwing custom exception (homework)
r/javahelp on Reddit: Help with throwing custom exception (Homework)
January 29, 2021 -

I don't really work with exception handling a lot, so I'm out of my comfort zone for this assignment. In essence, the code I'm testing is a List object, checking it to see if the object I want to add already exists within the list, and throwing a custom exception if it does. I'm using junit testing, if that matters.

public void addConnection(LinkedInUser user) throws LinkedInException
{
	try {
		for (int x = 0; x < connections.size(); x++)
		{
			if (connections.get(x) == user)
				throw new LinkedInException();
		}
		//if (connections.contains(user))
		//	throw new LinkedInException();
		//else
		connections.add(user);
	} catch (LinkedInException e) {
		e.Exception("You are already connected with this user");
	}
}

The commented portion was the old code. I think the problem is determining whether or not the object is already within the list, but I could be wrong. The LinkedInException class is just an empty class. Our instructor told us to override the five Exception class constructors, but that was it, so the overrides are blank.

Here's the junit test code

@Test
public void errorCheckAddCon()
{
	LinkedInUser test = new LinkedInUser("han", "password123");
	LinkedInUser test1 = new LinkedInUser("luke", "password123");
	boolean exceptionThrown = false;
	
	try {
		test.addConnection(test1);
		test.addConnection(test1);
	} catch (LinkedInException e) {
		exceptionThrown = true;
	}
	
	Assert.assertTrue(exceptionThrown);
}

(I think it's the addConnection method, and specifically the List.contains method within, because I manually set boolean exceptionThrown to true, and the junit test passed, so the junit test code isn't the issue here I believe)

Top answer
1 of 2
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 2
1
Why do you have a try-catch block in the addConnection method? Like what purpose do you think it serves?
Discussions

How to create a custom exception type in Java? - Stack Overflow
To raise an exception, simply pass ... throw new MyFormatExpcetion("spaces are not allowed"); -- you could even use the standard ParseException, without "creating" a custom exception type. ... See video tutorials about exception class creation and handling in Java... More on stackoverflow.com
🌐 stackoverflow.com
Is it bad practice to throw multiple custom exceptions in Java? - Software Engineering Stack Exchange
I'm developing a Java web application. It is a three layered architecture: web > service > repository. I'm thinking of creating many exceptions - each specific to each individual error and in the More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
November 6, 2015
java - Throwing custom exceptions in library: do I throw concrete ones or their superclass? - Software Engineering Stack Exchange
I am designing a library that abstracts a typical CRUD http service named FooService. In this library I am throwing different exceptions like FooServiceClientException for network related errors or More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 4, 2018
How to Create and Handle a Custom Exception in Java - LambdaTest Community
What is the correct way to create a Java custom exception? I want to define my own exception type and throw it when a specific condition is met. For example, in a try block, I read a string using reader.readLine(), and if the string contains a space, I need to throw my custom exception. More on community.lambdatest.com
🌐 community.lambdatest.com
0
March 16, 2025
🌐
DZone
dzone.com › data engineering › databases › implementing custom exceptions in java
Implementing Custom Exceptions in Java
November 13, 2017 - That’s all you need to do to implement a custom checked exception. You can now throw the MyBusinessException in your code, specify it as part of your method signature and handle it in a catch clause.
🌐
LabEx
labex.io › tutorials › java-creating-custom-java-exceptions-117405
Java Exception Handling | Custom Exceptions | LabEx
In addition, we define a throwable ... exception is ArrayIndexOutOfBounds. We can update the get() method in the MyArray class to throw the custom unchecked exception....
🌐
W3Schools
w3schools.com › java › java_try_catch.asp
Java Exceptions (Try...Catch)
The throw statement allows you to create a custom error. The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, ...
Top answer
1 of 9
273

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception
{
      // Parameterless Constructor
      public WordContainsException() {}

      // Constructor that accepts a message
      public WordContainsException(String message)
      {
         super(message);
      }
 }

Usage:

try
{
     if(word.contains(" "))
     {
          throw new WordContainsException();
     }
}
catch(WordContainsException ex)
{
      // Process message however you would like
}
2 of 9
131

You need to create a class that extends from Exception. It should look like this:

public class MyOwnException extends Exception {
    public MyOwnException () {

    }

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

    public MyOwnException (Throwable cause) {
        super (cause);
    }

    public MyOwnException (String message, Throwable cause) {
        super (message, cause);
    }
}

Your question does not specify if this new exception should be checked or unchecked.

As you can see here, the two types are different:

  • Checked exceptions are meant to flag a problematic situation that should be handled by the developer who calls your method. It should be possible to recover from such an exception. A good example of this is a FileNotFoundException. Those exceptions are subclasses of Exception.

  • Unchecked exceptions are meant to represent a bug in your code, an unexpected situation that you might not be able to recover from. A NullPointerException is a classical example. Those exceptions are subclasses of RuntimeException

Checked exception must be handled by the calling method, either by catching it and acting accordingly, or by throwing it to the calling method. Unchecked exceptions are not meant to be caught, even though it is possible to do so.

Top answer
1 of 5
7

Is it bad practice to throw multiple custom exceptions in Java?

No. It is good practice.

The only situation where multiple exceptions might be a (slightly) bad idea is if there is absolutely no possibility (ever!) of catching individual exceptions; i.e. the fine-grained exceptions won't serve any functional purpose. However, my opinion is that if you can make that assertion, then there is probably something wrong with the way that you / your team is using Java. And the counter-argument is that sensible use of multiple custom exceptions will help you to document the APIs ... even if you are never going to do more than catch-log-and-bail-out at runtime.

This is not to say that lots of custom exceptions will always be good:

  • If you go overboard and create a separate exception for everything, then you are probably adding unnecessary complexity. (In a lot of cases, different exception messages are sufficient.)

  • If you don't have a sensible inheritance hierarchy for your custom exceptions, then you may end up regretting it. (A well-designed hierarchy allows you to catch "classes" of exceptions, or declare methods as throwing them. It can make your code simpler.)

2 of 5
7

Is it bad practice to throw multiple custom exceptions in Java?

Generally speaking: No. Why should it?

As with everything: Abstraction is your friend.

Is it necessarry to have a CustomerNotFound Exception and a ProductNotFound Exception? Or are your requirements just a more abstract NotFoundException? The context could help to determine, what was missing. Having different exceptions for the sake of having them is nonsense.

Is it necessary, each layer of your application having custom exceptions? Exceptions are a way to report, that an intended action failed due to some reason.

  • Say, you have a controller which asks the service-layer to retrieve data, which in turn asks the DA-layer to read values from the DB. The resultset is empty. The service gets the empty resultset and throws a NotFoundException the service communicates, the failure of the action due to a missing result.

  • Say, the controller needs the service to do the payrolls for employees. And the service is asked to do the payroll for the employee with ID 123456, and in turn asks a service to retrieve the employee - but no emloyee could be found.

There are two ways to deal with that:

1) You throw a NotFound exception in the DA-Layer, catch it in the payroll-service and rethrow a PayrollServiceException wrapping the NotFoundException with the message Exmployee could not be found

2) You throw a NotFound exception in the DA-Layer and do not catch it in the payroll service and catch it instead a layer above.

I would go for (2), since in (1) the information, that the action failed because of a missing employee is redundant.

Find elsewhere
Top answer
1 of 2
3

Throwing a generic exception like FooServiceException makes your method signature easy to read, but you're also assuming the caller is not likely going to want to differentiate. If he did, he could still do so, but he'd have to pilfer through your code to find out which specific implementations of FooServiceException are thrown. Don't make the caller do that! That is why we can't have nice things!

On the other hand, if your method getById is throwing FooConnectionTimeoutException, FooConnectionPoolExhaustedException, FooTableNotFoundException, FooServiceObjectNotFoundException, clearly something is not right about this either. But fear no more, my good OP! There is a solution.

You can organize exceptions by type, then throw a reasonably generic exception for each type possible. In other words, have FooConnectionTimeoutException, FooConnectionPoolExhaustedException, FooTableNotFoundException all derive from FooDatabaseException. Your method signature then becomes:

getById(int id) throws FooServiceObjectNotFoundException, FooDatabaseException;

See how nice this is? Callers wanting to cover any and all exceptions would look no further than handling just FooServiceObjectNotFoundException and FooDatabaseException. Callers wanting to perform a different action upon FooServiceObjectNotFoundException can do so no qualms.

You can further organize according to necessity if you want to be more detailed, but the level of detail is entirely up to you. The key point here being that you have full control over how specific you want your exceptions to be. As a general rule, try to reduce the number of exceptions thrown to 3 or less. Anything beyond that is somewhat unnecessary, especially if many of the exceptions are related to the same type of issue (unexpected problems, business errors, invalid input, etc.).

2 of 2
0

The exception specification is an addendum to the return value, so it should follow similar guidelines.

I would suggest that you use the least specific type that satisfies the needs of the consuming code. In your case that might be FooServiceException, but it's equally plausible that Exception or Throwable is sufficient. You don't detail the members of FooServiceException, so I can't tell.

🌐
Baeldung
baeldung.com › home › java › core java › create a custom exception in java
Create a Custom Exception in Java | Baeldung
May 11, 2024 - try (Scanner file = new Scanner(new ... the root cause of the exception. To fix this, we can also add a java.lang.Throwable parameter to the constructor....
🌐
Quora
quora.com › When-should-I-use-custom-exception-in-Java
When should I use custom exception in Java? - Quora
Answer (1 of 4): If you have enough time, use one every time you catch a standard exception with intention to rethrow, and every time none of the standard exceptions are appropriate for the exact problem you’re seeing. In the former case, define a higher-level exception, then wrap the lower-level...
🌐
JetBrains
blog.jetbrains.com › idea › 2024 › 03 › easy-hacks-how-to-throw-java-exceptions
Easy Hacks: How to Throw Java Exceptions | The IntelliJ IDEA Blog
March 12, 2024 - By making information about potential exceptions available, any caller can decide what to do with the exception: ignore it by adding a throws to the method signature or catch the exception and handle it.
🌐
LambdaTest Community
community.lambdatest.com › general discussions
How to Create and Handle a Custom Exception in Java - LambdaTest Community
March 16, 2025 - What is the correct way to create a Java custom exception? I want to define my own exception type and throw it when a specific condition is met. For example, in a try block, I read a string using reader.readLine(), and …
🌐
Oracle
docs.oracle.com › javase › tutorial › essential › exceptions › throwing.html
How to Throw Exceptions (The Java™ Tutorials > Essential Java Classes > Exceptions)
The pop method checks to see whether any elements are on the stack. If the stack is empty (its size is equal to 0), pop instantiates a new EmptyStackException object (a member of java.util) and throws it. The Creating Exception Classes section in this chapter explains how to create your own exception classes.
🌐
Tutorialspoint
tutorialspoint.com › java › java_custom_exception.htm
Java - Custom Exception
Here is the syntax to create a custom class in Java - ... You just need to extend the predefined Exception class to create your own Exception. These are considered to be checked exceptions. Keep the following points in mind when writing your own exception classes − · All exceptions must ...
🌐
Programiz
programiz.com › java-programming › examples › create-custom-exception
Java Program to Create custom exception
import java.util.ArrayList; import java.util.Arrays; // create a unchecked exception class class CustomException extends RuntimeException { public CustomException(String message) { // call the constructor of RuntimeException super(message); } } class Main { ArrayList<String> languages = new ArrayList<>(Arrays.asList("Java", "Python", "JavaScript")); // check the exception condition public void checkLanguage(String language) { // throw exception if language already present in ArrayList if(languages.contains(language)) { throw new CustomException(language + " already exists"); } else { // insert
🌐
Alvin Alexander
alvinalexander.com › java › java-custom-exception-create-throw-exception
Java: How to create and throw a custom exception | alvinalexander.com
August 4, 2024 - As you can see, all you need to do to throw your custom exception is (1) create a new instance of the exception (new AlsCustomException("Anything but zero ...")), and then (2) throw that exception with the throw keyword. With those two pieces in place, we'll create a "driver" class with a main ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › exceptions-in-java
Java Exception Handling - GeeksforGeeks
In Java, all exceptions and errors are subclasses of the Throwable class.
Published   1 month ago
🌐
CodingNomads
codingnomads.com › what-are-custom-exceptions-java
Custom Exceptions in Java
To create a subclass of Exception, you need to create a class that extends the Exception class. As a result, your Exception class inherits all of the methods declared in the Throwable class (because Exception is a subclass of Throwable).
🌐
Medium
medium.com › @salvipriya97 › custom-exceptions-in-java-301ef3b568a3
Custom Exceptions in Java. What is a Custom Exception? | by Priya Salvi | Medium
February 13, 2024 - When deciding whether to extend ... in Java, it's essential to understand the implications of each and choose based on the specific requirements and characteristics of your application. Here are some guidelines to consider: ... If the exceptional condition is recoverable or expected to be handled by the caller, consider extending Exception. Checked exceptions require explicit handling through try-catch blocks or declaring them in the method signature using throws...
🌐
Rosa Fiore
rosafiore.eu › home › how to throw custom exceptions with spring boot
How to Throw Custom Exceptions with Spring Boot - Rosa Fiore
August 20, 2020 - With the class for ExceptionResponse done, I can now start with handling the thrown exceptions. For this, I’ve created the ExceptionResponseHandler that inherits the ResponseEntityExceptionHandler class. It is also annotated with @ControllerAdvice. This annotation allows me to create one class that handles all exceptions for every controller in my application.