Exception Handling in Java
1. Introduction
In Java, Exception Handling is a mechanism that allows a program to detect and handle
runtime errors without terminating abnormally. It provides a way to maintain normal
application flow even when unexpected events occur.
2. What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. It represents an error condition or unexpected behavior.
Examples: ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,
FileNotFoundException.
3. Difference Between Error and Exception
Error Exception
Occurs due to system failure or serious problems. Occurs due to issues in code logic or user input.
Cannot be recovered. Can be handled using try-catch.
Example: OutOfMemoryError, StackOverflowError Example: IOException, ArithmeticException
4. Exception Hierarchy
Throwable → Exception → (Checked & Unchecked) and Error. Checked exceptions are
detected at compile-time, while unchecked exceptions occur at runtime.
5. Keywords Used in Exception Handling
Keyword Description
try Defines a block of code where exceptions may occur.
catch Handles exceptions thrown by try block.
finally Executes code whether exception occurs or not.
throw Used to manually throw an exception.
throws Declares exceptions that a method might throw.
6. Example Code
try { int a = 10 / 0; } catch (ArithmeticException e) { [Link]("Error: Division by
zero not allowed."); } finally { [Link]("Program ended safely."); }
7. Advantages of Exception Handling
• Prevents abnormal termination of program.
• Makes code more readable and maintainable.
• Separates error-handling from main logic.
• Improves reliability and debugging process.
8. Common Exception Classes
Exception Description
ArithmeticException Occurs when dividing by zero.
NullPointerException Accessing a null object.
ArrayIndexOutOfBoundsException Invalid array index access.
FileNotFoundException File not found error.
IOException Input/Output related issue.
9. Summary
Exception Handling in Java provides a structured way to detect and manage errors using
try, catch, throw, throws, and finally keywords. It ensures smoother program execution and
better control over runtime issues.