Java Exception Handling Explained: A Complete How-To Guide


Handling exceptions is an essential part of writing robust and error-free Java applications. Without proper exception handling, a small runtime error can crash an entire program. Java provides a structured approach to managing exceptions, ensuring that applications run smoothly even when unexpected errors occur.
In this guide, we'll cover everything you need to know about exception handling in Java, including types of errors, exception hierarchy, try-catch, throw vs throws, custom exceptions, and best practices.
πΉ 1. Types of Errors in Java
Before diving into exceptions, it's important to understand three main types of errors in Java:
1οΈβ£ Compile-Time Errors
These errors occur during compilation due to incorrect syntax or missing elements.
β Example (Syntax Error):
System.out.println("Hello); // β Missing closing quote causes a compile-time error
βοΈ Solution: Javaβs compiler detects and reports these errors, so you must fix them before running the program.
2οΈβ£ Logical Errors (Bugs)
The program runs without crashing, but produces incorrect results due to incorrect logic.
β Example (Logic Error):
int result = 2 + 2; // Expecting 4, but mistakenly coded as 5
βοΈ Solution: Debugging and testing help identify and fix logical errors.
3οΈβ£ Runtime Errors (Exceptions)
These errors occur during execution and may stop the program abruptly if not handled properly.
β Example (Division by Zero - ArithmeticException):
int a = 10 / 0; // β ArithmeticException: Division by zero
βοΈ Solution: Use exception handling to catch such errors and prevent program crashes.
πΉ 2. What are Exceptions in Java?
An exception is an unexpected event that occurs during program execution, disrupting the normal flow. Java provides a built-in way to handle exceptions, ensuring programs remain stable.
π Why Handle Exceptions?
βοΈ Prevents application crashes in critical systems (e.g., banking, medical software).
βοΈ Improves user experience (graceful error messages instead of abrupt crashes).
βοΈ Ensures smooth execution by allowing the program to recover.
πΉ 3. Exception Handling in Java (Try-Catch Mechanism)
Java provides the try-catch block to handle exceptions and prevent program termination.
β Basic Syntax of Try-Catch
try {
// Code that may cause an exception
} catch (ExceptionType e) {
// Handle the exception
}
β Example: Handling Division by Zero
try {
int result = 10 / 0; // π¨ Throws ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
π οΈ How It Works?
1οΈβ£ Code inside try
executes first.
2οΈβ£ If an exception occurs, Java jumps to the catch
block.
3οΈβ£ If no exception occurs, the catch
block is skipped.
πΉ 4. Handling Multiple Exceptions
A program may throw different exceptions, and Java allows handling them separately using multiple catch
blocks.
β Example: Handling Multiple Exceptions
try {
int[] arr = new int[5];
arr[10] = 50; // π¨ ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error");
} catch (Exception e) {
System.out.println("Some other error occurred");
}
βοΈ Order of Catch Blocks:
πΉ Specific exceptions first (e.g., ArrayIndexOutOfBoundsException
).
πΉ General exceptions last (Exception
is the parent of all exceptions).
πΉ 5. Exception Hierarchy in Java
Java exceptions follow this class hierarchy:
Object
β
βββ Throwable
βββ Exception (Handleable)
β βββ IOException
β βββ SQLException
β βββ RuntimeException (Unchecked)
β βββ ArithmeticException
β βββ NullPointerException
β βββ ArrayIndexOutOfBoundsException
β
βββ Error (Non-recoverable)
βββ OutOfMemoryError
βββ StackOverflowError
πΉ 6. throw
vs throws
in Java
β
throw
(Manually Throw an Exception)
Used inside a method to generate an exception.
public void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
System.out.println(a / b);
}
β
throws
(Declares Exceptions in a Method)
Used in the method declaration to indicate possible exceptions.
public void readFile() throws IOException {
FileReader file = new FileReader("data.txt");
}
βοΈ Key Difference:
throw
is used inside a method to generate exceptions.throws
declares exceptions a method might throw.
πΉ 7. Creating Custom Exceptions
When built-in exceptions donβt fit, we can create custom exceptions.
β Step 1: Create Custom Exception Class
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
β Step 2: Use Custom Exception
public class Main {
public static void checkAge(int age) throws MyException {
if (age < 18) {
throw new MyException("Age must be 18 or above");
}
}
public static void main(String[] args) {
try {
checkAge(16);
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
πΉ 8. Best Practices for Exception Handling
βοΈ Use specific exceptions instead of Exception
class.
βοΈ Log exceptions properly instead of just printing.
βοΈ Use finally
block for cleanup (closing files, databases).
βοΈ Avoid empty catch blocks (catch (Exception e) {}
).
βοΈ Donβt use exceptions for normal program flow.
πΉ 9. Real-World Use Cases
1οΈβ£ Banking Application (InsufficientBalanceException
)
if (balance < amount) {
throw new InsufficientBalanceException("Insufficient funds!");
}
2οΈβ£ File Handling in Web Applications (IOException
)
public void readFile(String filename) throws IOException {
FileReader file = new FileReader(filename);
}
3οΈβ£ Database Connectivity (SQLException
)
try {
Connection con = DriverManager.getConnection(DB_URL, USER, PASS);
} catch (SQLException e) {
System.out.println("Database connection failed!");
}
π― Conclusion
βοΈ Java provides try-catch
, throw
, throws
, and finally
for exception handling.
βοΈ Understanding checked vs unchecked exceptions is crucial.
βοΈ Custom exceptions improve error specificity.
In upcoming articles, Iβll expand on these topics in more detail. Follow me for more Java content! ππ₯
Subscribe to my newsletter
Read articles from Arkadipta Kundu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Arkadipta Kundu
Arkadipta Kundu
Iβm a Computer Science undergrad from India with a passion for coding and building things that make an impact. Skilled in Java, Data Structures and Algorithms (DSA), and web development, I love diving into problem-solving challenges and constantly learning. Right now, Iβm focused on sharpening my DSA skills and expanding my expertise in Java development.