How to throw multiple custom exceptions in Java

If in a try block we need to handle the multiple exceptions then we need to write exception handler or catch block for each type of exception. catch block to use multiple exceptions. If a catch block handles more than one exception ,then catch parameter is implicitly final.

Can a Java method throw multiple exceptions?

A method can throw one of several exceptions. You cannnot (in Java or in any language AFAIK) throw simultaneously two exceptions, that would not make much sense. You can also throw a nested Exception, which contains inside another one exception object.

How do you create a custom exception in Java?

How can we create a custom exception in Java?

  1. CustomException class is the custom exception class this class is extending Exception class.
  2. Create one local variable message to store the exception message locally in the class object.
  3. We are passing a string argument to the constructor of the custom exception object.

How can we create custom checked and custom unchecked exception in Java?

Custom Checked and Custom Unchecked

  1. All exceptions must be a child of Throwable.
  2. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
  3. If you want to write a runtime exception, you need to extend the RuntimeException class.

How do I create a custom checked exception?

To create a checked custom exception, it must extend Exception or its child classes. Unchecked custom exception extends RuntimeException or its child classes. All Exceptions are a child of Throwable.

How to create multiple custom exceptions in Java?

However, rather than having to create multiple files for every custom exception I want, or bloating my main class file, I’d like to put all of my custom exceptions in this class and invoke them via a method

What are the best practices for custom exceptions?

There are 4 general best practices that you should follow when you decide to implement a custom exception class. These recommendations make your code and API easier to understand. They also reduce the required amount of documentation.

Can a custom exception be unchecked in Java?

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 which returns the first line of the file: ? The code above is a classic way of handling Java checked exceptions.

How to get the cause of an exception in Java?

You should implement at least one constructor that gets the causing Throwable as a parameter and sets it on the superclass. public class MyBusinessException extends Exception { public MyBusinessException(String message, Throwable cause, ErrorCode code) { super(message, cause); this.code = code; }

Java exceptions FAQ: How do I create a custom exception in Java?

As a solution, here’s a quick example that shows how to create and throw a custom exception class in Java. In this tutorial I'll demonstrate how to:

  • Create a custom exception class in Java
  • Throw our custom Java exception
  • Catch our custom exception, and
  • Look at the output from our custom exception when we print a stack trace

A Java custom exception class

To get started, this is pretty much the most simple possible Java custom exception class. As you can see, to create a custom exception class, all you have to do is extend the Java Exception class, and create a simple constructor:

/** * My custom exception class. */ class AlsCustomException extends Exception { public AlsCustomException(String message) { super(message); } }

As you'll see later there are more Exception class constructors you can override, but this is a good start for our example.

A method to throw a custom Java exception

To demonstrate how to throw our exception, here's a small example class with a method named getBar that will throw our custom exception (AlsCustomException) if the method is given the value of zero as a parameter (sorry, not much imagination there, just trying to keep it simple):

/** * Our test class to demonstrate our custom exception. */ class Foo { public String getBar(int i) throws AlsCustomException { if (i == 0) { // throw our custom exception throw new AlsCustomException("Anything but zero ..."); } else { return "Thanks"; } } }

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.

A driver class to test (throw) the custom Java exception

With those two pieces in place, we'll create a "driver" class with a main method to test our custom Java exception. In our main method, we'll create a new instance of our Foo class, then call the getBar method with the value of zero, which makes that method throw our custom Java exception:

/** * A class to test (throw) the custom exception we've created. * @author alvin alexander, devdaily.com * */ public class JavaCustomExceptionExample { public static void main(String[] args) { // create a new foo Foo foo = new Foo(); try { // intentionally throw our custom exception by // calling getBar with a zero String bar = foo.getBar(0); } catch (AlsCustomException e) { // print the stack trace e.printStackTrace(); } } }

Output from a driver class

With all those pieces in place, when we compile and run our Java source code, we get the following output when we print our stack trace:

AlsCustomException: Anything but zero ... at Foo.getBar(JavaCustomExceptionExample.java:37) at JavaCustomExceptionExample.main(JavaCustomExceptionExample.java:18)

As you can see, our custom exception output looks a lot like the output from any other Java exception that you've seen. The name of our exception is shown on the first line of the stack trace, followed by our error message.

I hope this is all pretty straightforward. As a friend of mine used to say, "this isn't too hard ... once you know how to do it." :)

Java Exception class constructors

For more information on the topic of Java exceptions, check out the Java Exception class javadoc. As you'll see in that javadoc, the Exception class has the following constructors. We only overloaded one of these constructors, but in your own custom exception class you may want to override several of them:

  1. Exception()
  2. Exception(String message)
  3. Exception(String message, Throwable cause)
  4. Exception(Throwable cause)

Download the custom exception source code

If you're interested in running your own Java custom exception tests, feel free to download our Java custom exception example source code. All of the Java source code shown above is included in this one file.

In my experience (I am a Java developer for 10+ years now) it is bad practice. Not that it is a code smell, but it most often hinders you in your daily work.

Think of an application that tries to read a file and probably throws an FileNotReadableException. After a while you realize, that the file may not be readable due to insufficient access-rights. What do you do? Change the name of the exception - no, it may be still in use. Add a subtype FileNotReadableBecauseOfAccessRightsException? Well, this is rather 2 errors - not readable + access rights, but the root cause is the rights thing. So you add an InsufficientAccessRightsException somewhere else in the class tree. When doing so you also need to change the code where the original exception was caught since its 2 different types now (a violation of the open-closed-principle). And so on... And what's the gain? ... in contrast to an exception with a message? Static type safety. In the context of exceptions it is only useful to prevent typos. A developer could still use a wrong exception type (e.g. EntryNotFoundException instead of FileNotReadableException).

As said by dwoz: an exception is just a class.

My experience is that a few exceptions are sufficient. What you want to express are error-messages - for several messages you only need 1 (runtime) exception with a String field. All exceptions should be caught by a default error-handler at the highest possible layer (or earlier if necessary).

Besides the usual message, you sometimes need to store more information, like a filesystem-path, a username, a device-id, a uuid to more easily trace the error in a distributed system, etc. for those purposes I suggest to create custom exception classes.

As said by amon, a rule of thumb should be: for libraries use (some) exceptions, for (web-) applications us as few as possible