Advertisement
Google Ad Slot: content-top
Java Exception
Exception handling in Java is a mechanism that allows you to handle runtime errors so that normal program flow is not disrupted. It helps prevent unexpected crashes and improves application stability.
What is an Exception?
An exception is an unwanted or unexpected event that occurs during program execution. It disrupts the normal flow of instructions.
Types of Exceptions
- Checked Exceptions (Compile-time)
- Exceptions checked by the compiler.
- Example:
IOException,SQLException - Unchecked Exceptions (Runtime)
- Occur at runtime and are not checked at compile-time.
- Example:
NullPointerException,ArithmeticException - Errors (System failures)
- Related to system failures and cannot be handled.
- Example:
OutOfMemoryError,StackOverflowError
Exception Handling Keywords:
Java provides five keywords for exception handling:
Keyword |
Description |
|---|---|
try |
Defines a block of code to test for exceptions. |
catch |
Handles the exception if one occurs. |
finally |
A block that executes always, whether an exception occurs or not. |
throw |
Used to manually throw an exception. |
throws |
Declares exceptions that a method might throw. |
Basic try-catch Example
Multiple catch Example:
You can handle different exceptions separately using multiple catch blocks.
finallyBlock (Always Executes)
The finally block always executes whether an exception occurs or not.
Using throw to Manually Throw an Exception:
Using throws to Declare Exceptions
If a method does not handle an exception, it can declare it using throws.
Custom Exception (User-Defined Exception):
You can create your own exception class by extending Exception.