Custom Exceptions in Java
In this article, create a custom exception class in Java.
Join the DZone community and get the full member experience.
Join For FreeWe 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
- How to create a custom exception class
- Throw the custom Java exception
- Catch the custom exception
- Check the output
Java Custom Exception:
The below class is a simple java class to create custom exception.
xxxxxxxxxx
class CustomExceptionEx extends Exception
{
public CustomExceptionEx(String string)
{
//calling the super
super(string);
}
}
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.
class Sample
{
public String checkNum(int num)
throws CustomExceptionEx
{
if (i == 0)
{
//throwing the exception
throw new CustomExceptionEx("Number is zero");
}
else
{
return "Number is non zero";
}
}
}
Steps to Throw Exception:
- Create instance of exception CustomExceptionEx
- Throw exception using throw keyword
- 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.
xxxxxxxxxx
public class MainClass
{
public static void main(String[] args)
{
Sample object = new Sample();
try
{
//calling the method
String bar = object.checkNum(0);
}
catch (CustomExceptionEx e)
{
e.printStackTrace();
}
}
}
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!
Published at DZone with permission of Shatakshi Dixit. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments