Java Exception Handling: Try, Catch, Finally, and Throw
During program execution, various issues can occur such as invalid input,
incorrect logic, or
unexpected runtime conditions. When these situations arise, Java generates
an exception,
which interrupts the normal flow of the program.
Without proper handling, an exception will cause the program to terminate
abruptly. To prevent
this, Java provides a mechanism called exception handling, which allows
developers to detect,
manage, and recover from runtime errors gracefully.
This guide explains how to handle exceptions in Java using try, catch,
finally, and throw, along
with practical examples.
What is an Exception in Java?
An exception is an event that occurs during program execution and disrupts
the normal flow of
instructions.
When a problem occurs, Java throws an exception, which generates an error
message and
stops the program unless it is properly handled.
Common causes of exceptions include:
- Invalid user input
- Accessing elements outside an array’s bounds
- Dividing a number by zero
- Attempting to use an object that has not been initialized
Exception Handling in Java (Try and Catch)
Java uses the try-catch mechanism to handle runtime errors.
- try block – Contains code that may produce an exception.
- catch block – Handles the exception if one occurs.
This prevents the program from crashing and allows developers to define
alternative actions.
Basic Syntax
try {
// Code that might cause an exception
}
catch (Exception e) {
// Code that handles the exception
}
Example: Exception Without Handling
Consider the following program that attempts to access an invalid array
index.
public class ArrayErrorDemo {
public static void main(String[] args) {
int[] scores = {85, 90, 78};
System.out.println(scores[5]); // Invalid index
}
}
Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException
The program crashes because the array index 5 does not exist.
Example: Handling the Exception Using Try-Catch
By using a try-catch block, we can prevent the program from crashing and
display a
user-friendly message.
public class SafeArrayAccess {
public static void main(String[] args) {
try {
int[] scores = {85, 90, 78};
System.out.println("Accessing array
element...");
System.out.println(scores[5]);
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Attempted to access an
invalid array index.");
}
System.out.println("Program continues running.");
}
}
Output
Accessing array element...
Error: Attempted to access an invalid array index.
Program continues running.
Now the program handles the error gracefully and continues execution.
The Finally Block
The finally block contains code that will always execute whether an
exception occurs or not.
It is typically used for important tasks such as:
- Closing files
- Releasing system resources
- Cleaning up operations
Syntax
try {
// Risky code
}
catch (Exception e) {
// Exception handling
}
finally {
// Code that always runs
}
Example: Using the Finally Block
public class FinallyExample {
public static void main(String[] args) {
try {
int number = 20;
int divisor = 0;
int result = number / divisor;
System.out.println("Result: " + result);
}
catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
}
finally {
System.out.println("Execution of
try-catch block completed.");
}
}
}
Output
Cannot divide by zero.
Execution of try-catch block completed.
The finally block executes regardless of the exception.
The Throw Keyword
Java also allows developers to manually generate exceptions using the throw
keyword.
This is useful when you want to enforce custom validation rules in your
program.
Syntax
throw new ExceptionType("Error message");
Example: Throwing a Custom Exception
The following program checks whether a user is eligible to register for an
exam.
public class EligibilityChecker {
static void verifyAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Registration
failed: Minimum age is 18.");
}
System.out.println("Registration successful.");
}
public static void main(String[] args) {
verifyAge(16);
}
}
Output
Exception in thread "main" java.lang.IllegalArgumentException:
Registration failed: Minimum age is 18.
If we change the value to:
verifyAge(21);
Output
Registration successful.
The program only throws an exception when the validation condition fails