Exception Handling is one of the most important features of Java that allows a program to handle runtime errors gracefully without terminating unexpectedly.
Normally, when an error occurs during program execution, Java stops the program immediately. By using Exception Handling, we can catch these errors and continue executing the remaining code.
In simple words:
Exception Handling is a mechanism to detect, handle, and recover from runtime errors.
For example:
Suppose a user enters 0 as a divisor while dividing two numbers.
Without exception handling:
- The program crashes.
- Remaining code never executes.
With exception handling:
- Java catches the error.
- Displays a meaningful message.
- Continues executing the remaining program.
Why Do We Need Exception Handling?
Exception Handling helps developers:
- Prevent application crashes
- Handle unexpected runtime errors
- Improve application reliability
- Improve user experience
- Simplify debugging
- Build secure enterprise applications
What is an Exception?
An Exception is an event that interrupts the normal execution of a program.
Example:
10 / 0
Produces:
ArithmeticException
Types of Exceptions
Java exceptions are mainly divided into:
1. Checked Exceptions
Checked during compilation.
Examples:
- IOException
- SQLException
- FileNotFoundException
2. Unchecked Exceptions
Occur during runtime.
Examples:
- ArithmeticException
- NullPointerException
- ArrayIndexOutOfBoundsException
- NumberFormatException
Exception Handling Keywords
Java provides five important keywords:
trycatchfinallythrowthrows
Exception Handling Flow
Program Starts
│
▼
try Block
│
Exception?
│ │
No Yes
│ │
▼ ▼
Continue catch Block
│
▼
finally Block
│
▼
Program Ends
Real-World Uses of Exception Handling
Exception handling is used in:
- Banking Applications
- ATM Software
- Payment Gateways
- Hospital Management Systems
- Android Applications
- Spring Boot Applications
- Database Applications
- File Management Systems
Before Learning This Chapter
You should already understand:
- Variables
- Methods
- Classes
- Inheritance
- Polymorphism
- Abstraction
- Interfaces
In this chapter, you’ll solve practical Java Exception Handling programs frequently asked in coding interviews, university exams, and Java developer assessments. Java Exception Handling practice questions with solutions help to understand the concepts.
1. Java Program to Handle ArithmeticException
Problem Statement
Write a Java program to handle ArithmeticException when dividing a number by zero.
Java Solution
public class Main {
public static void main(String[] args) {
try {
int result = 20 / 0;
System.out.println(result);
}
catch (ArithmeticException exception) {
System.out.println("Cannot divide by zero.");
}
}
}
Sample Output
Cannot divide by zero.
Explanation
The division operation throws an ArithmeticException.
The catch block catches the exception and displays a meaningful message instead of terminating the program.
Concepts Covered
- try Block
- catch Block
- ArithmeticException
- Runtime Exception
2. Java Program to Handle ArrayIndexOutOfBoundsException
Problem Statement
Write a Java program to handle an ArrayIndexOutOfBoundsException.
Java Solution
public class Main {
public static void main(String[] args) {
int[] numbers = {10, 20, 30};
try {
System.out.println(numbers[5]);
}
catch (ArrayIndexOutOfBoundsException exception) {
System.out.println("Invalid Array Index.");
}
}
}
Sample Output
Invalid Array Index.
Explanation
The array contains only three elements.
Attempting to access index 5 generates an ArrayIndexOutOfBoundsException.
The exception is handled using the catch block.
Concepts Covered
- Arrays
- Runtime Exception
- try-catch
- ArrayIndexOutOfBoundsException
3. Java Program to Handle NullPointerException
Problem Statement
Write a Java program to handle NullPointerException.
Java Solution
public class Main {
public static void main(String[] args) {
String text = null;
try {
System.out.println(text.length());
}
catch (NullPointerException exception) {
System.out.println("String object is null.");
}
}
}
Sample Output
String object is null.
Explanation
Since the string reference points to null, calling length() throws a NullPointerException.
The exception is handled gracefully using the catch block.
Concepts Covered
- NullPointerException
- try-catch
- Exception Handling
- Runtime Errors
4. Java Program to Handle NumberFormatException
Problem Statement
Write a Java program to handle a NumberFormatException when converting a string into an integer.
Java Solution
public class Main {
public static void main(String[] args) {
String value = "Java";
try {
int number = Integer.parseInt(value);
System.out.println(number);
}
catch (NumberFormatException exception) {
System.out.println("Invalid Number Format.");
}
}
}
Sample Output
Invalid Number Format.
Explanation
The Integer.parseInt() method converts a string into an integer.
Since "Java" is not a valid numeric value, Java throws a NumberFormatException.
The catch block handles the exception and prevents the program from crashing.
Concepts Covered
- NumberFormatException
- Integer.parseInt()
- try-catch
- Runtime Exception
5. Java Program to Demonstrate Multiple Catch Blocks
Problem Statement
Write a Java program to demonstrate Multiple Catch Blocks.
Java Solution
public class Main {
public static void main(String[] args) {
try {
String value = null;
System.out.println(value.length());
}
catch (ArithmeticException exception) {
System.out.println("Arithmetic Exception Occurred.");
}
catch (NullPointerException exception) {
System.out.println("Null Pointer Exception Occurred.");
}
catch (Exception exception) {
System.out.println("General Exception Occurred.");
}
}
}
Sample Output
Null Pointer Exception Occurred.
Explanation
A try block can be followed by multiple catch blocks.
Java checks each catch block from top to bottom.
The first matching exception is executed, and the remaining catch blocks are skipped.
Important: Always place the general
Exceptionclass at the end; otherwise, the compiler will report an error because it would make the more specific catch blocks unreachable.
Concepts Covered
- Multiple Catch Blocks
- Exception Hierarchy
- NullPointerException
- Exception Class
6. Java Program to Demonstrate Finally Block
Problem Statement
Write a Java program to demonstrate the use of the finally block.
Java Solution
public class Main {
public static void main(String[] args) {
try {
int result = 20 / 0;
System.out.println(result);
}
catch (ArithmeticException exception) {
System.out.println("Cannot Divide by Zero.");
}
finally {
System.out.println("Finally Block Always Executes.");
}
}
}
Sample Output
Cannot Divide by Zero.
Finally Block Always Executes.
Explanation
The finally block is always executed, regardless of whether an exception occurs or not.
It is commonly used for:
- Closing database connections
- Closing files
- Releasing network resources
- Cleaning up memory
Even if an exception is thrown and handled, the finally block still runs.
Concepts Covered
- finally Block
- Resource Cleanup
- Exception Handling
- try-catch-finally
7. Java Program to Demonstrate the throw Keyword
Problem Statement
Write a Java program to demonstrate the use of the throw keyword.
Java Solution
public class Main {
public static void main(String[] args) {
int age = 15;
try {
if (age < 18) {
throw new ArithmeticException("Not Eligible to Vote");
}
System.out.println("Eligible to Vote");
}
catch (ArithmeticException exception) {
System.out.println(exception.getMessage());
}
}
}
Sample Output
Not Eligible to Vote
Explanation
The throw keyword is used to manually create and throw an exception.
It is useful when developers want to validate input and generate custom error conditions.
Syntax:
throw new ExceptionType("Message");
Concepts Covered
- throw Keyword
- Manual Exception
- Input Validation
- Exception Object
8. Java Program to Demonstrate the throws Keyword
Problem Statement
Write a Java program to demonstrate the use of the throws keyword.
Java Solution
import java.io.IOException;
public class Main {
static void check() throws IOException {
throw new IOException("File Not Found");
}
public static void main(String[] args) {
try {
check();
}
catch (IOException exception) {
System.out.println(exception.getMessage());
}
}
}
Sample Output
File Not Found
Explanation
The throws keyword is used in a method declaration to indicate that the method may throw one or more exceptions.
The calling method is responsible for handling those exceptions.
Example syntax:
void methodName() throws IOException
Concepts Covered
- throws Keyword
- Checked Exceptions
- IOException
- Method Declaration
9. Java Program to Handle FileNotFoundException
Problem Statement
Write a Java program to handle FileNotFoundException.
Java Solution
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Main {
public static void main(String[] args) {
try {
File file = new File("student.txt");
FileInputStream input = new FileInputStream(file);
}
catch (FileNotFoundException exception) {
System.out.println("File Does Not Exist.");
}
}
}
Sample Output
File Does Not Exist.
Explanation
When Java cannot locate the specified file, it throws a FileNotFoundException.
This is a Checked Exception, so it must be handled using either:
- try-catch
- throws
Concepts Covered
- File Handling
- FileInputStream
- FileNotFoundException
- Checked Exceptions
10. Java Program to Demonstrate Nested Try-Catch
Problem Statement
Write a Java program to demonstrate Nested Try-Catch blocks.
Java Solution
public class Main {
public static void main(String[] args) {
try {
try {
int result = 10 / 0;
}
catch (ArithmeticException exception) {
System.out.println("Inner Catch Block");
}
}
catch (Exception exception) {
System.out.println("Outer Catch Block");
}
}
}
Sample Output
Inner Catch Block
Explanation
A try block can be placed inside another try block.
This is called Nested Try-Catch.
If the inner block handles the exception, the outer catch block is not executed.
Nested try-catch is useful when different sections of code require separate exception handling.
Concepts Covered
- Nested Try-Catch
- Exception Propagation
- Inner Catch
- Outer Catch
11. Java Program to Create a Custom Exception
Problem Statement
Write a Java program to create and use a Custom Exception.
Java Solution
class InvalidAmountException extends Exception {
InvalidAmountException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
int amount = -500;
try {
if (amount < 0) {
throw new InvalidAmountException("Amount Cannot Be Negative");
}
System.out.println("Valid Amount");
}
catch (InvalidAmountException exception) {
System.out.println(exception.getMessage());
}
}
}
Sample Output
Amount Cannot Be Negative
Explanation
A Custom Exception is created by extending the Exception class.
Custom exceptions are useful when built-in exceptions do not clearly represent business rules.
In this example, negative transaction amounts are not allowed, so a custom exception is thrown.
Concepts Covered
- Custom Exception
- Exception Class
- throw Keyword
- Business Validation
12. Java Program to Handle Invalid Age Using Custom Exception
Problem Statement
Write a Java program to throw a custom exception when the user’s age is less than 18.
Java Solution
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
int age = 16;
try {
if (age < 18) {
throw new InvalidAgeException("Age Must Be 18 or Above");
}
System.out.println("Eligible");
}
catch (InvalidAgeException exception) {
System.out.println(exception.getMessage());
}
}
}
Sample Output
Age Must Be 18 or Above
Explanation
The program checks the user’s age.
If the age is below 18, a custom exception is thrown.
Otherwise, the user is considered eligible.
This technique is commonly used in:
- Banking
- Government Portals
- Job Applications
- Online Registration Systems
Concepts Covered
- Custom Exception
- Age Validation
- throw Keyword
- Exception Handling
13. Java Program to Demonstrate Exception Propagation
Problem Statement
Write a Java program to demonstrate Exception Propagation.
Java Solution
public class Main {
static void divide() {
int result = 20 / 0;
}
public static void main(String[] args) {
try {
divide();
}
catch (ArithmeticException exception) {
System.out.println("Exception Propagated Successfully");
}
}
}
Sample Output
Exception Propagated Successfully
Explanation
The divide() method does not handle the exception.
Instead, the exception is automatically passed to the calling method.
This process is called Exception Propagation.
The main() method catches the exception.
Concepts Covered
- Exception Propagation
- Method Calls
- ArithmeticException
- try-catch
14. Java Program to Handle Multiple Exceptions in One Program
Problem Statement
Write a Java program to handle multiple exceptions in a single program.
Java Solution
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {10, 20};
System.out.println(numbers[5]);
int result = 10 / 0;
}
catch (ArrayIndexOutOfBoundsException exception) {
System.out.println("Array Index Error");
}
catch (ArithmeticException exception) {
System.out.println("Arithmetic Error");
}
catch (Exception exception) {
System.out.println("General Exception");
}
}
}
Sample Output
Array Index Error
Explanation
The first exception encountered is the array index error.
Once it is caught, the remaining statements inside the try block are skipped.
Only one catch block executes for a particular exception.
Concepts Covered
- Multiple Exceptions
- Exception Hierarchy
- ArrayIndexOutOfBoundsException
- ArithmeticException
15. Java Program to Create a Real-World Banking System Using Exception Handling
Problem Statement
Write a Java program to create a simple banking system that throws an exception when the withdrawal amount exceeds the available balance.
Java Solution
class InsufficientBalanceException extends Exception {
InsufficientBalanceException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
int balance = 5000;
int withdraw = 7000;
try {
if (withdraw > balance) {
throw new InsufficientBalanceException("Insufficient Balance");
}
balance -= withdraw;
System.out.println("Remaining Balance : " + balance);
}
catch (InsufficientBalanceException exception) {
System.out.println(exception.getMessage());
}
}
}
Sample Output
Insufficient Balance
Explanation
The program compares the withdrawal amount with the available balance.
If the withdrawal amount exceeds the balance, a custom exception is thrown.
This approach is commonly used in:
- Banking Systems
- ATM Software
- Payment Applications
- Wallet Systems
Concepts Covered
- Custom Exception
- Banking Example
- Business Rule Validation
- Exception Handling
Chapter Summary
In this chapter, you learned Java Exception Handling, one of the most important concepts for writing robust and reliable Java applications. Exception handling enables programs to detect, manage, and recover from runtime errors instead of terminating unexpectedly.
You practiced handling both built-in and custom exceptions while learning how Java manages program flow when an error occurs.
Throughout this chapter, you covered:
- Introduction to Exceptions
- Checked Exceptions
- Unchecked Exceptions
- try Block
- catch Block
- finally Block
- throw Keyword
- throws Keyword
- Multiple Catch Blocks
- Nested Try-Catch
- Exception Propagation
- Custom Exceptions
- Real-world Banking Example
These concepts are widely used in enterprise Java applications, Android development, Spring Boot projects, and web applications.
Key Takeaways
- Exception Handling prevents unexpected program termination.
- Java exceptions are classified into:
- Checked Exceptions
- Unchecked Exceptions
- The
tryblock contains code that may generate an exception. - The
catchblock handles exceptions. - The
finallyblock always executes (except in rare cases such as JVM shutdown). - The
throwkeyword is used to manually throw an exception. - The
throwskeyword declares that a method may throw exceptions. - Custom exceptions improve code readability and business rule validation.
- Multiple catch blocks allow handling different exception types separately.
- Exception handling improves application reliability, maintainability, and user experience.
Frequently Asked Questions (FAQs)
1. What is Exception Handling in Java?
Exception Handling is a mechanism that allows Java programs to handle runtime errors gracefully without stopping the execution of the entire program.
2. What is the difference between Checked and Unchecked Exceptions?
| Checked Exception | Unchecked Exception |
|---|---|
| Checked during compilation | Occurs during runtime |
| Must be handled | Optional to handle |
| Example: IOException | Example: ArithmeticException |
3. What is the purpose of the try block?
The try block contains code that may generate an exception during execution.
Example:
try {
int result = 10 / 0;
}
4. What is the purpose of the finally block?
The finally block executes regardless of whether an exception occurs.
It is mainly used for resource cleanup, such as:
- Closing files
- Closing database connections
- Releasing network resources
5. What is the difference between throw and throws?
| throw | throws |
|---|---|
| Used to manually throw an exception | Declares exceptions in a method signature |
| Used inside a method | Used in method declaration |
6. What is a Custom Exception?
A Custom Exception is a user-defined exception created by extending the Exception class.
It helps represent application-specific errors more clearly.
7. What is Exception Propagation?
Exception Propagation occurs when a method does not handle an exception, causing Java to pass the exception to the calling method.
8. Where is Exception Handling used in real-world applications?
Exception Handling is commonly used in:
- Banking Systems
- ATM Machines
- Payment Gateways
- Android Applications
- Spring Boot Projects
- Hospital Management Systems
- File Management Software
- E-commerce Applications
- REST APIs
- Enterprise Java Applications
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
