User Defined Exception in Java
โก Smart Summary
User Defined Exception in Java lets you create your own exception class by extending the Exception class and raising it with the throw keyword. This resource explains what custom exceptions are, when to use them, and how to build one with a complete working example.

What is User Defined Exception in Java?
A User Defined Exception, or custom exception, means creating your own exception class and throwing that exception using the ‘throw’ keyword. This can be done by extending the class Exception.
There is no need to override any of the above methods available in the Exception class in your derived class. But practically, you will require some amount of customizing as per your programming needs.
When to Use User-Defined Exceptions in Java?
User-defined exceptions in Java are custom exceptions created to handle specific error conditions in your application. They provide flexibility by allowing developers to define their own error scenarios.
- Handle Specific Application Errors: If your application encounters a scenario that standard exceptions cannot cover, create a user-defined exception to address that situation.
- Enhance Readability and Debugging: User-defined exceptions offer more clarity by explicitly indicating the issue, making debugging easier.
- Ensure Clean Code Structure: These exceptions help maintain clean code, as they separate error-handling logic from the core functionality.
- Improve Code Maintenance: User-defined exceptions allow you to update error handling without modifying the entire code, making maintenance more efficient.
Example: To create a User-Defined Exception class.
Step 1) Copy the following code into the editor.
class JavaException { public static void main(String args[]) { try { throw new MyException(2); // throw is used to create a new exception and throw it. } catch (MyException e) { System.out.println(e); } } } class MyException extends Exception { int a; MyException(int b) { a = b; } public String toString() { return ("Exception Number = " + a); } }
Step 2) Save, Compile & Run the code. Expected output:
NOTE: The keyword “throw” is used to create a new exception and throw it to the catch block.

