Join Our 4-Week Free Gen AI Course with select Programs.

Request a callback

or Chat with us on

Custom Exceptions in Java – How to Implement It (With Examples)

Basics of Python
Basics of Python
icon
5 Hrs. duration
icon
9 Modules
icon
1800+ Learners
logo
Start Learning

Ever faced an error in your Java program that wasn’t covered by the standard exceptions and wondered how to handle it? Maybe something very specific to your app?

 

That’s where the custom exceptions in Java come in.

 

Creating custom exceptions allows you to handle unique situations in your code. You can make your errors clearer and more meaningful.

 

This blog will guide you through creating a custom exception in Java. We’ll cover the steps and differences between checked and unchecked exceptions and provide practical examples.

Why Custom Exceptions Are Essential in Java Programming

Imagine you’re building a banking app and need to check for a specific error that the standard exceptions don’t cover: A user tries to withdraw more money than they have.

 

A standard exception might not provide the best feedback. But, a custom exception can give a clear, understandable error message.

 

A custom exception can:

 

  • Handle errors specific to your application.
  • Make your code easier to understand.
  • Provide clear messages to users and developers.
  • Handle business rules and workflows.

 

Also Read: Types of Exceptions in Java

Steps to Create a Custom Exception in Java

Creating a custom exception in Java is straightforward. Here’s a step-by-step guide:

Define a New Class that Extends the Exception Class

First, create a new class that extends the Exception class.

class MyCustomException extends Exception { public MyCustomException(String message) { super(message); } }

This class is now your custom exception.

Using the super() Method

Use the super() method to pass a message to the parent class.

public MyCustomException(String message) { super(message); }

This lets you set a custom error message when the exception is thrown.

 

Overriding the toString() Method

 

Override the toString() method to customise the error message.

@Override public String toString() { return "MyCustomException: " + getMessage(); }

This makes your exception message more readable.

Detailed Explanation of Checked vs. Unchecked Exceptions

Java exceptions fall into two categories: checked and unchecked. Understanding the difference is crucial.

Checked Exceptions

  • Extend the Exception class.
  • Must be caught or declared in the method signature.
  • Must handle these exceptions in your code.
class FileNotFoundException extends Exception { public FileNotFoundException(String message) { super(message); } }

Unchecked Exceptions

  • Extend the RuntimeException class.
  • Do not need to be caught or declared.
  • They can be ignored, but it’s better to handle them.
class IllegalArgumentException extends RuntimeException { public IllegalArgumentException(String message) { super(message); } }
DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Practical Examples of Implementing Custom Exceptions

Example 1: Handling Invalid User Input with Custom Exceptions

Imagine you’re developing an app and need to validate user input. What if the input is empty or null? A custom exception can make this clear and simple.

class InvalidUserInputException extends Exception { public InvalidUserInputException(String message) { super(message); } } public class UserInputHandler { public void validateInput(String input) throws InvalidUserInputException { if (input == null || input.isEmpty()) { throw new InvalidUserInputException("Input cannot be null or empty"); } } public static void main(String[] args) { UserInputHandler handler = new UserInputHandler(); try { handler.validateInput(""); } catch (InvalidUserInputException e) { System.out.println(e.getMessage()); } } }

Output:

output

In this example, InvalidUserInputException is thrown when the input is invalid. It makes the code easy to read and understand.

Example 2: Creating a Custom Exception for File Operations

Handling file operations can get tricky. What if a file doesn’t exist? A custom exception can help here, too.

import java.io.File; class FileProcessingException extends Exception { public FileProcessingException(String message) { super(message); } } class FileHandler { public void readFile(String filePath) throws FileProcessingException { if (!new File(filePath).exists()) { throw new FileProcessingException("File not found: " + filePath); } // File processing logic } } public class Main { public static void main(String[] args) { FileHandler handler = new FileHandler(); try { handler.readFile("nonexistent.txt"); } catch (FileProcessingException e) { System.out.println(e.getMessage()); } } }

Output:

output

Here, FileProcessingException makes it clear that the issue is with the file. It tells the user exactly what went wrong.

Example 3: Using Custom Exceptions for Business Logic

Business logic can be complex. For instance, what if there are not enough funds for a transaction? A custom exception makes this specific and understandable.

class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { super("Insufficient funds for transaction. Required: " + amount); this.amount = amount; } public double getAmount() { return amount; } } public class BankAccount { private double balance; public BankAccount(double balance) { this.balance = balance; } public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount); } balance -= amount; } public static void main(String[] args) { BankAccount account = new BankAccount(100); try { account.withdraw(150); } catch (InsufficientFundsException e) { System.out.println(e.getMessage()); } } }

Output:

custom exception in java

With InsufficientFundsException, the error message directly tells the user why the transaction failed.

Example 4: Custom Exception for Database Operations

Connecting to a database can also throw specific errors. A custom exception can handle these neatly.

class DatabaseConnectionException extends Exception { public DatabaseConnectionException(String message) { super(message); } } public class DatabaseHandler { public void connect(String connectionString) throws DatabaseConnectionException { if (connectionString == null || connectionString.isEmpty()) { throw new DatabaseConnectionException("Database connection string cannot be null or empty"); } // Database connection logic } public static void main(String[] args) { DatabaseHandler handler = new DatabaseHandler(); try { handler.connect(""); } catch (DatabaseConnectionException e) { System.out.println(e.getMessage()); } } }

 

Output:

output

This example shows DatabaseConnectionException to handle connection issues specifically.

Example 5: Network Communication Custom Exception

Network operations often face errors. A custom exception makes error handling more straightforward.

class NetworkCommunicationException extends Exception { public NetworkCommunicationException(String message) { super(message); } } public class NetworkHandler { public void sendRequest(String url) throws NetworkCommunicationException { if (url == null || url.isEmpty()) { throw new NetworkCommunicationException("URL cannot be null or empty"); } // Network communication logic } public static void main(String[] args) { NetworkHandler handler = new NetworkHandler(); try { handler.sendRequest(""); } catch (NetworkCommunicationException e) { System.out.println(e.getMessage()); } } }

 

Output:

output

Using NetworkCommunicationException, the code makes it clear when a URL is invalid.

Best Practices for Defining Custom Exception in Java

Creating custom exceptions is useful, but there are best practices to follow.

  • Use clear, meaningful names for your exceptions.
  • Provide detailed error messages.
  • Include extra fields if necessary to convey more information.
  • Don’t create custom exceptions for situations already covered by standard exceptions.
  • Clearly document the purpose of each custom exception.

Conclusion

The custom exception in Java is the tool for handling particular error conditions. They make your code cleaner, clearer, and easier to maintain.

 

In this article, we have gone through the power of custom exceptions in Java. We have learnt how to handle certain error conditions by creating our own exceptions. We have covered practical examples that range from user input to file operations, business logic, database connections, and networking.

 

Custom exceptions in Java make your code more readable, maintainable, and precise. Following the best practices, you will efficiently deal with failures and increase the overall effectiveness of your applications.

FAQs
  • Checked exceptions must either be declared or caught, whereas unchecked is not required to be handled explicitly.
  • Use them for specific error conditions not covered by standard exceptions, especially for business logic.
  • Yes, extend the RuntimeException class.
  • Use a constructor in your exception class that calls the superclass constructor with the message.
  • No, use them selectively for specific scenarios. Standard exceptions should cover common errors.

Deploying Applications Over the Cloud Using Jenkins

Prashant Kumar Dey

Prashant Kumar Dey

Associate Program Director - Hero Vired

Ex BMW | Google

24 October, 7:00 PM (IST)

Limited Seats Left

Book a Free Live Class

left dot patternright dot pattern

Programs tailored for your success

Popular

Management

Data Science

Finance

Technology

Future Tech

Upskill with expert articles

View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.
Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

|

Sitemap

© 2024 Hero Vired. All rights reserved