{{announcement.body}}
{{announcement.title}}

Custom Exceptions in Java

DZone 's Guide to

Custom Exceptions in Java

In this article, create a custom exception class in Java.

· Java Zone ·
Free Resource

We can create custom exception class in Java very easily. It can either be a checked or unchecked exception.

Let's create a simple example to check creation of custom exceptions in Java.

We will learn

  1. How to create a custom exception class
  2. Throw the custom Java exception
  3. Catch the custom exception
  4. Check the output

Java Custom Exception:

The below class is a simple java class to create custom exception.

Java
 




xxxxxxxxxx
1
13


1
class CustomExceptionEx extends Exception
2
3
{
4
5
  public CustomExceptionEx(String string)
6
7
  {
8
    //calling the super
9
    super(string);
10
11
  }
12
13
}



Steps to Create Exception:

  • Create a java class
  • Extend the Exception class
  • call the super()

There exists other constructors in the Exception class as well. This is the basic example to create a custom exception. It is the most used way.

Throw Java Custom Exception

In the above example, we have created a custom exception - CustomExceptionEx.

Now, let's throw this exception in our java code example.

Java
 







Steps to Throw Exception:

  1. Create instance of exception CustomExceptionEx
  2. Throw exception using throw keyword
  3. Declare the exception in the method using throws keyword

Test Java Custom Exception

Now, create a main class and test the created java custom exception.

Java
 




xxxxxxxxxx
1
17


 
1
public class MainClass
2
{
3
  public static void main(String[] args)
4
  {
5
   
6
    Sample object = new Sample();
7
    
8
    try
9
    {
10
      //calling the method
11
      String bar = object.checkNum(0);
12
    }
13
    catch (CustomExceptionEx e)
14
    {
15
      e.printStackTrace();
16
    }
17
  }
18
}



In the above class, we are calling the  checkNum  method of  Sample  class, which is throwing the custom created exception.

It was simple, right? If you have any questions, please post in the comments.

Thanks for reading!

Topics:
Java Custom Exception, exception in java, java, tutorial

Published at DZone with permission of Shatakshi Dixit . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}