Exception
An exception is an unexpected event or error that occurs during the execution of a program and
disrupts its normal flow.
Examples:
Dividing a number by zero
Accessing an invalid array index
Trying to open a file that does not exist
When such errors occur, an exception is “thrown.” If the program does not handle it, the program
will terminate abnormally.
Types of Exceptions
1. Checked Exceptions (compile-time exceptions – mostly in
Java)
These are exceptions that the compiler checks during compilation.
The programmer must handle them using try/catch or throws.
Examples:
IOException
SQLException
FileNotFoundException
Meaning: These exceptions are expected and can be recovered from.
2. Unchecked Exceptions (runtime exceptions)
These occur during execution and are usually due to logical errors in the program.
Examples:
ArithmeticException (e.g., divide by zero)
NullPointerException
ArrayIndexOutOfBoundsException
Meaning: These usually indicate mistakes in program logic.
3. Errors
These are serious problems that a program cannot handle.
Examples:
OutOfMemoryError
StackOverflowError
Meaning: These are not exceptions and should not be handled by programs.
Exception Handling Methods
Exception handling is a technique used to detect and respond to errors in a program without
stopping its execution abruptly.
Java provides five main mechanisms:
1. try
2. catch
3. finally
4. throw
5. throws
1. try–catch Block
The code that may generate an exception is placed in a try block.
Errors are handled in the catch block.
Example:
public class Example1 {
public static void main(String[] args) {
try {
int a = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
[Link]("Error: Cannot divide by zero!");
}
[Link]("Program continues...");
}
}
Explanation:
Code inside try may fail.
When division by zero occurs, control jumps to the catch block.
The program does not crash—it prints a message and continues
2. Multiple catch Blocks
Used when different exceptions need different handling.
try {
int arr[] = new int[5];
arr[10] = 20; // ArrayIndexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e)
{
[Link]("Invalid index");
}
catch (Exception e)
{
[Link]("General exception");
}
Explanation:
Java checks catch blocks top to bottom.
The most specific exception must come first.
If the first catch does not match, Java tries the next.
3. finally Block
The finally block executes whether an exception occurs or not.
It is used for cleanup tasks such as:
closing files
closing database connections
releasing memory/resources
✅ Example 3: finally always executes
public class Example3 {
public static void main(String[] args) {
try {
int a = 5 / 0;
} catch (ArithmeticException e) {
[Link]("Exception caught!");
} finally {
[Link]("Finally block always executes.");
}
}
}
Output:
Exception caught!
Finally block always executes.
4. throw Keyword (Manual Exception
Throwing)
Used when a programmer wants to manually throw an exception.
✅ Example 4: throw
public class Example4 {
public static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote!");
} else {
[Link]("Eligible to vote!");
}
}
public static void main(String[] args) {
checkAge(16);
}
}
✔ Explanation:
Exception is created manually using throw.
Method stops immediately when exception is thrown.
⭐ 5. throws Keyword
Used in the method signature to indicate that the method may throw an exception.
It forces the calling method to handle the exception.
✅ Example 5: throws
import [Link].*;
public class Example5 {
public static void readFile() throws IOException {
FileReader fr = new FileReader("[Link]"); // May cause IOException
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
[Link]("File not found!");
}
}
}
✔ Explanation:
readFile() declares that it may throw IOException.
The calling method (main()) must handle it with a try-catch.
⭐ 6. Nested try–catch Blocks
A try block inside another try block.
✅ Example 6: Nested try
public class Example6 {
public static void main(String[] args) {
try {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Inner catch: Divide by zero!");
}
int arr[] = new int[3];
arr[5] = 10; // Outer exception
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Outer catch: Invalid index!");
}
}
}
⭐ 7. try-with-resources (for automatic
resource closing)
Introduced in Java 7.
Automatically closes resources.
✅ Example 7: try-with-resources
import [Link].*;
public class Example7 {
public static void main(String[] args) {
try (FileReader fr = new FileReader("[Link]")) {
// Read file here
} catch (IOException e) {
[Link]("Error occurred while reading file.");
}
}
}
✔ Benefit:
No need for a finally block to close the file.
The difference between throw and throws:
✅ Difference Between throw and throws
Point of
throw throws
Difference
Used to actually throw an exception Used to declare that a method may
Definition
manually throw exceptions
Point of
throw throws
Difference
Where used Inside a method or block In the method signature/header
To delegate exception handling
Purpose To explicitly generate an exception
responsibility to the caller
Type of
Runtime operation Compile-time declaration
operation
Number of Can declare multiple exceptions
Can throw only one exception at a time
exceptions separated by commas
Must be handled by surrounding try– Caller method must handle or
Who handles it?
catch block further declare it
void method() throws
Syntax throw new Exception("Message");
IOException, Exception
throw new void readFile() throws
Example ArithmeticException("Error"); IOException
Time of
Occurs during program execution Checked at compile time
occurrence