Built-in and custom exceptions
Java provides a rich Exception Handling mechanism that allows us to:
-
Use built-in exceptions for common error conditions.
-
Create our own custom exceptions to represent application-specific problems.
🔹 1. Built-in Exceptions
🔸 What are they?
These are predefined exception classes in the Java standard library (in java.lang
and other packages).
🔸 Types:
Category | Examples |
---|---|
Unchecked Exceptions (subclass of RuntimeException ) | ArithmeticException , NullPointerException , ArrayIndexOutOfBoundsException |
Checked Exceptions (subclass of Exception but not RuntimeException ) | IOException , SQLException , ClassNotFoundException |
📘 Example: Using a Built-in Exception
🔹 2. Custom Exceptions
🔸 What are they?
Custom (user-defined) exceptions are classes you create by extending the Exception
class (or its subclasses) to represent specific error conditions in your application.
✅ Why use custom exceptions?
-
To provide meaningful names to exceptions.
-
To handle business logic errors more cleanly.
-
To keep the code more readable and modular.
🔧 How to Create a Custom Exception
Step 1: Create a class that extends Exception
or RuntimeException
Step 2: Use throw
and throws
to use it
🔁 Comparison Table
Feature | Built-in Exceptions | Custom Exceptions |
---|---|---|
Defined by | Java API (java.lang , java.io , etc.) | Programmer/User-defined |
Purpose | Handle general errors like null, IO, etc. | Handle application-specific errors |
Need to write new class? | ❌ No | ✅ Yes |
Examples | NullPointerException , IOException | InsufficientFundsException , InvalidInputException |
Extend from | Exception or RuntimeException | Same |
🧠 Best Practice
-
Use built-in exceptions for general coding errors.
-
Use custom exceptions to clearly indicate and handle business rule violations or application-specific issues.
Comments
Post a Comment