Exception Handling in Java
🔷 Introduction to Exception Handling in Java
Exception Handling in Java is a powerful mechanism that allows a program to detect and respond to run-time errors (exceptions) gracefully, without crashing the program.
Exceptions are unexpected events that disrupt the normal flow of a program, such as:
-
Division by zero
-
File not found
-
Null pointer access
-
Array index out of bounds
✅ Why Exception Handling?
-
To handle errors effectively and maintain normal application flow.
-
To separate error-handling code from regular code.
-
To provide meaningful error messages to users.
-
To prevent program termination due to runtime errors.
✅ Exception Handling Keywords
Keyword | Description |
---|---|
try | Defines a block of code to monitor for exceptions |
catch | Defines a block to handle the exception |
finally | Block that always executes, used for cleanup code |
throw | Used to explicitly throw an exception |
throws | Declares the exceptions a method might throw |
🔁 Basic Example
✅ Types of Exceptions
1. Checked Exceptions
-
These are exceptions that are checked at compile-time.
-
The compiler ensures that the programmer handles them.
-
Must be caught using
try-catch
or declared usingthrows
.
Examples:
-
IOException
-
SQLException
-
ClassNotFoundException
2. Unchecked Exceptions
-
These occur at runtime and are not checked at compile-time.
-
Caused by programming errors, and optional to handle.
Examples:
-
ArithmeticException
-
NullPointerException
-
ArrayIndexOutOfBoundsException
✅ Exception Class Hierarchy
Comments
Post a Comment