exceptions

Java Custom Exception Example

Photo of Chandan SinghChandan SinghNovember 3rd, 2014Last Updated: November 3rd, 2014
0 500 3 minutes read

In this example we will look briefly at the basics ofException, in Java Programming Language. We will also see, how to create a customException Class.

1. Basics of Exception

As per oracle docs,An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program’s instructions.

In laymen terms, when a condition occurs, in which the routine is not sure how to proceed in an ordinary way it creates an object of exception and hands it over to the runtime system to find an appropriate handler for the exception object. In case, the runtime system does not find an appropriate handler in the call hierarchy the runtime system terminates.

The exceptions havejava.lang.Throwable as their superclass.The three main categories of Exceptional conditions are :

  • Error(represented byjava.lang.Error and its sub-classes)
  • Checked Exception(represented by direct subclasses ofjava.lang.Exception exceptjava.lang.RuntimeException)
  • Unchecked or Runtime Exceptions (represented byjava.lang.RuntimeException and its sub-classes)

Errors : Errors denote serious abnormal condition with the application likeOutOfMemoryError orVirtualMachineError. Any reasonable application should not try to recover from such a condition.

Runtime Exception/Unchecked Exception : These types of exceptions usually indicate programming errors likeNullPointerException orIllegalArgumentException. The application may or may not choose to recover from the condition.

Checked Exception : An application is supposed to catch these types of exceptions and recover reasonably from them. Examples includeFileNotFoundException andParseException.

2. Creating custom Exception

The first thing before creating a custom exception, the developer should be able to justify the creation. As per Java Docs,You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else’s.

  • Do you need an exception type that isn’t represented by those in the Java platform?
  • Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
  • Does your code throw more than one related exception?
  • If you use someone else’s exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?

Now, that you are sure that you really do want a create a custom Exception class we will begin writing the actual program.
To create a custom checked exception, we have to sub-class from thejava.lang.Exception class. And that’s it! Yes, creating a custom exception in java is simple as that!

public class CustomException extends Exception{}

Sometimes though, theCustomException object will have to be constructed from another exception. So its important that we create a constructor for such a scenario.

So a more complete class would be as below :

CustomException.java:

package com.javacodegeeks.examples.exception;public class CustomException extends Exception{    private static final long serialVersionUID = 1997753363232807009L;public CustomException(){}public CustomException(String message){super(message);}public CustomException(Throwable cause){super(cause);}public CustomException(String message, Throwable cause){super(message, cause);}public CustomException(String message, Throwable cause,                                            boolean enableSuppression, boolean writableStackTrace){super(message, cause, enableSuppression, writableStackTrace);}}

2.1 Testing the custom Exception :

CustomExceptionTest.java:

package com.javacodegeeks.examples.exception;public class CustomExceptionTest{    public static void main(String[] args)    {try        {      testException(null);        }        catch (CustomException e)        {      e.printStackTrace();        }    }    public static void testException(String string) throws CustomException    {      if(string == null)    throw new CustomException("The String value is null");    }}

Similarly, an unchecked exception can be created by sub-classing from thejava.lang.RuntimeException
Class.

public class CustomException extends RuntimeException{...}

3. Points to note

  • An unchecked exception should be preferred to a checked exception. This will help programmes to be free of unnecessarytry..catch blocks.
  • Exceptions are abnormal conditions, and as such should not be used for controlling the flow of execution of the programmes(as demonstrated by example below).
try{for (int i = 0;; i++){System.out.println(args[i]);}}catch (ArrayIndexOutOfBoundsException e){// do nothing}
  • Acatch block should not be empty as shown in the example above. Such exceptions are very difficult to track, since there is no logging.
  • The name of a custom exception class should end with Exception. It improves the readability of the code. Instead of naming the class InvalidSerial, the class should be named InvalidSerialException.
  • When using ARM/try-with-resources blocks, if exception gets suppressed by the try-with-resources statement, we can useThrowable#getSuppressed() method.

4. Closing Words

Here,we tried to understand the basics of exception and how to create a custom exception of our own. We learned the best practices while creating a custom exception class and also how to handle an exception in a reasonable manner.

Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Chandan SinghChandan SinghNovember 3rd, 2014Last Updated: November 3rd, 2014
0 500 3 minutes read
Photo of Chandan Singh

Chandan Singh

Chandan holds a degree in Computer Engineering and is a passionate software programmer. He has good experience in Java/J2EE Web-Application development for Banking and E-Commerce Domains.
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.