Exception in Java
⚠️ What is an Exception in Java?
An Exception is an unexpected event that occurs during the execution of a program and disrupts its normal flow.
🔥 It represents runtime errors like division by zero, file not found, or null reference access.
🔧 Types of Exceptions:
1. Checked Exceptions
- Checked at compile time
- Must be handled using
try-catch
or declared withthrows
✅ Examples:
IOException
SQLException
FileNotFoundException
2. Unchecked Exceptions
- Checked at runtime
- Caused by programming errors
- Not required to handle explicitly
✅ Examples:
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
3. Errors (Not Exceptions technically)
- Serious problems that cannot be handled by the program
- Example:
OutOfMemoryError
,StackOverflowError
🚧 Exception Hierarchy:
🔁 Handling Exceptions:
try-catch-finally
block:
throws
keyword:
✅ Summary:
Feature | Description |
---|---|
What is it? | Runtime event disrupting normal flow |
Types | Checked, Unchecked, Errors |
Handled using |
try-catch , throws , finally
|
Common examples |
NullPointerException , IOException , ArrayIndexOutOfBoundsException
|
☄️ throw
vs throws
– Key Difference
Keyword | Purpose | Used For | Position in Code |
---|---|---|---|
throw |
Actually throws an exception | Inside a method/block | Inside method body |
throws |
Declares an exception | In method signature | After method declaration |
🔹 throw
Keyword
- Used to explicitly throw an exception (checked or unchecked).
- Only one exception can be thrown at a time.
✅ Syntax:
throw new ExceptionType("Error message");
🔍 Example:
🔸 throws
Keyword
- Used to declare exceptions a method might throw.
- Compiler checks if checked exceptions are handled or declared.
✅ Syntax:
returnType methodName() throws ExceptionType1, ExceptionType2 { }
🔍 Example:
🧠 Example Using Both:
-
throws
declares the method might throwIllegalArgumentException
-
throw
actually throws the exception if condition fails
✅ Summary:
Feature | throw |
throws |
---|---|---|
Action | Actually throws an exception | Declares an exception |
Used in | Method body | Method signature |
Exceptions | One at a time | Multiple can be declared |
Purpose | Generate an exception manually | Inform caller to handle exception |
⚠️ What are Built-in Exceptions?
Built-in exceptions are predefined classes in Java provided by the JDK to handle common runtime and compile-time errors.
All exceptions extend from the Throwable
class.
🧩 Java Exception Hierarchy
✅ Common Built-in Exceptions
🔷 Checked Exceptions (Compile-time)
Exception | Description |
---|---|
IOException |
I/O failure like file not found |
FileNotFoundException |
File is missing while reading |
SQLException |
Database access errors |
ClassNotFoundException |
Class not found during runtime loading |
InterruptedException |
Thread interrupted during waiting |
🔒 Must be handled using try-catch
or declared using throws
.
🔶 Unchecked Exceptions (Runtime Exceptions)
Exception | Description |
---|---|
ArithmeticException |
Division by zero or other arithmetic errors |
NullPointerException |
Accessing object methods/fields with null
|
ArrayIndexOutOfBoundsException |
Accessing invalid array index |
NumberFormatException |
Converting string to number fails |
IllegalArgumentException |
Invalid arguments passed to a method |
ClassCastException |
Invalid object type casting |
🔓 No need to handle explicitly, but can cause crashes if ignored.
🔥 Errors (Not usually caught)
Error | Description |
---|---|
StackOverflowError |
Infinite recursion |
OutOfMemoryError |
Heap memory exhausted |
NoClassDefFoundError |
Class not found at runtime |
🧪 Example:
✅ Summary:
Category | Handled At | Examples |
---|---|---|
Checked Exceptions | Compile-time |
IOException , SQLException
|
Unchecked | Runtime |
NullPointerException , ArithmeticException
|
Errors | Usually not caught |
StackOverflowError , OutOfMemoryError
|
🔧 What is a Custom Exception?
A Custom Exception is a user-defined exception class that extends Java's Exception
or RuntimeException
.
It allows you to create meaningful and specific error messages for your application logic.
✅ When to Use:
- To handle domain-specific errors
- To make error handling more readable and maintainable
- To enforce business rules
🧱 Steps to Create a Custom Exception:
✅ 1. Extend Exception
(Checked) or RuntimeException
(Unchecked)
🔹 Example: Custom Checked Exception
🔸 Example: Custom Unchecked Exception
🧪 How to Use in Code
🔁 Summary Table
Base Class | Type | When Used |
---|---|---|
Exception |
Checked Exception | Must be caught or declared with throws
|
RuntimeException |
Unchecked | Optional to catch, used for programming logic |
💡 Tips:
- Add constructors for flexibility (with or without message)
- Avoid overusing unchecked exceptions unless truly logical
- Name your exceptions meaningfully (e.g.,
InsufficientBalanceException
,DataNotFoundException
)