DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo
  • Beyond Semantic Similarity: Designing Two-Stage RAG With Java

Trending

  • Deny by Default: Policy-as-Code Guardrails for Agents That Act
  • Function Calling: Responses API vs Chat Completions
  • Bolting an LLM Onto a System That Can't Afford to Be Wrong
  • Passwordless Image Pulls in Kubernetes With ServiceAccount Tokens and a Credential Provider

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Java
  4. Custom Exceptions in Java

Custom Exceptions in Java

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

By 
Shatakshi Dixit
·
May. 11, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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
 




x
18


 
1
class Sample
2
{
3
  public String checkNum(int num)
4
  throws CustomExceptionEx
5
  {
6
    if (i == 0)
7
    {
8
      //throwing the exception
9
      throw new CustomExceptionEx("Number is zero");
10
    }
11
    else
12
    {
13
      return "Number is non zero";
14
    }
15
  }
16
}



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!

Java (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • Smarter GitHub Copilot Prompts for Java Microservices: From APIs to Production Tests
  • Google Cloud Pub/Sub vs. AWS SNS and SQS: One Java API for Both With MultiCloudJ
  • Integration Testing With MongoDB in Java: Finding the @Sql Equivalent With Liquibase/Flyway or Jamolingo
  • Beyond Semantic Similarity: Designing Two-Stage RAG With Java

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook