Java Custom Exception

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

An exception in programming halts execution due to unexpected issues. Java permits custom exception creation, empowering developers to define specific error types. Custom exceptions, subclasses of the standard Exception class, enhance error handling. They're designed to fit application needs precisely, allowing for tailored error management. Creating a custom exception in Java involves extending the base Exception class and utilizing the throw keyword to raise instances when needed.

Why Use Custom Exceptions?

Custom exception in Java serves various purposes, enhancing error handling and code clarity. They're valuable for:

  1. Targeted Exception Handling: Custom exceptions allow specific handling of subsets of existing exceptions, ensuring precise error management tailored to application needs.
  2. Business Logic Clarification: By defining exceptions related to business logic or workflow, developers and users gain clarity on encountered issues, aiding in problem resolution and understanding.

Creating a custom exception in Java involves extending the Exception class from the java.lang package.

Consider a scenario where you're developing a banking application. You might encounter situations where the user attempts to withdraw more money than their account balance permits. In those situations, you can make your own special exception to deal with that exact problem.

Example 1

Let us see how custom checked-exception works. Let us create a class where we create a FileInputStream to read a file from the computer. Suppose that the user entered a file's name or path that is incorrect. At compile time only it will throw an exception that a file is not found and the user is unable to understand the issue. So we throw a custom FileException that explains the issue to the user and also shows the root cause.

We try to give a path to Stream for the file in the try-catch block. If the file exists, try block will execute. In case the file is not present, inside the catch block we throw a custom exception in java that makes the program more readable. We print StackTrace and message in the output.

It is a checked exception as it identifies if the file is present or not during compilation only.

Output:

Example 2

Let us take an example for Custom Unchecked Exception. Let us assume that there is a list of products from which the consumer is trying to fetch some item using the product key. Now if the product key is greater than the number of items in the product's list then we throw the ProductNotFound Exception. This also explains Consumer the cause of the exception.

bring() method throws a ProductNotFound Exception if it is not valid. This is called a Checked Exception as we can only know during runtime if we have a product at a particular product-key index. In the main method, we try to fetch some random products.

Output:

In the output, as 2 was a valid Product Key, it returned Washing Machine at index 1. But 6 was an invalid Product Key, the program throws a ProductNotFound Exception.

Explore Scaler Topics Java Tutorial and enhance your Java skills with Reading Tracks and Challenges.

Conclusion

  1. Clarity Enhancement: Custom exception in Java offer specific and informative error messages, aiding in debugging and comprehension.
  2. Precision in Handling: They enable tailored error management, distinguishing between different error types for appropriate handling.
  3. Business Logic Representation: Custom exception in Java can depict application-specific errors, facilitating easier understanding and resolution.
  4. Checked and Unchecked: They can be designed as checked or unchecked exceptions, providing control over error propagation.
  5. Maintainability Boost: Utilizing custom exception in Java leads to cleaner code, encapsulating error-handling logic and improving code readability.

See More