Next-Gen App & Browser Testing Cloud
Trusted by 2 Mn+ QAs & Devs to accelerate their release cycles

Learn how to handle runtime and compile-time errors effectively with exception handling methods in Java and Python, ensuring reliable and robust applications.

Tahneet Kanwal
December 30, 2025
Exceptions are events that occur when the program is running to signal the programmer that something unexpected has happened.
They can occur for various reasons, such as invalid code logic, external factors like device failures, or runtime issues like insufficient memory. Handling exceptions becomes important because it may interrupt the normal flow of the program.
Handling exceptions helps ensure that the program works as expected and also recovers from unexpected conditions by providing meaningful feedback on what went wrong. If these events are not handled properly, they can lead to the breakage or unexpected behavior of the code.
Exception handling is a technique in programming to handle runtime errors, allowing the program to execute and recover when unexpected situations occur. Instead of showing errors and terminating a program, exception handling provides a structure to deal with errors and manage them appropriately. With a special block of code called an exception handler, you can handle errors effectively.
In many programming languages, exception handling is added using try, catch blocks where:
This exception handler helps you handle various unexpected issues without terminating the program.
Here are the benefits of using exception handling:
Note: Master exception handling for reliable applications. Try TestMu AI Now!
Now that you understand exception handling and its benefits, let’s explore the different types of exception handling in popular programming languages like Java and Python.
Exception handling in Java can be handled using ClassNotFoundException, IOException, SQLException, and others to ensure the program keeps running.
When an exception occurs, the JVM creates an exception object containing details like the name and description of the issue and the program’s state when the exception happened.
If an appropriate handler is found, the exception is passed to it for processing. If no handler exists, the JVM’s default exception handler prints the exception details, including its type and location, and terminates the program abnormally. This process helps prevent unexpected crashes and provides meaningful error messages.
Java organizes exception classes in a hierarchy structure, defining relationships between general and more specific types of exceptions.
Java Exception Hierarchy:
In Java, all exceptions and errors inherit from the Throwable class, which is the root of the exception hierarchy. This hierarchy is divided into two main branches.
Below is the hierarchy of Java’s exception classes:

In Java, exceptions are broadly categorized into two types:
Common exceptions include:
Below is an example of a custom exception for invalid API responses during testing:
class ApiTesting {
public static void main(String[] args) {
try {
testApiResponse(500);
} catch (InvalidApiResponseException e) {
System.out.println(e);
}
}
static void testApiResponse(int statusCode) throws InvalidApiResponseException {
if (statusCode != 200) {
throw new InvalidApiResponseException(statusCode);
} else {
System.out.println("API response is valid.");
}
}
}
class InvalidApiResponseException extends Exception {
int statusCode;
InvalidApiResponseException(int statusCode) {
this.statusCode = statusCode;
}
public String toString() {
return "Invalid API Response: HTTP Status Code " + statusCode + ". Expected 200 OK.";
}
}
The program consists of two classes: ApiTesting and InvalidApiResponseException. The ApiTesting class checks the status code of an API response. If the code is not 200, it throws a custom exception, InvalidApiResponseException, which extends the Exception class. This exception stores the invalid status code and provides a custom error message.
In Java, there are five important keywords specifically used for handling exceptions in a program.
| Keyword | Description |
|---|---|
| try | Defines a block of code where exceptions might occur. It must be followed by either catch or finally. |
| catch | Handles exceptions that occur in the preceding try block. It cannot exist without a try block. |
| finally | Contains code that executes regardless of whether an exception occurs or is handled. |
| throw | Explicitly throws an exception. |
| throws | Declares potential exceptions that a method might throw. Used in method declarations. |
Here’s an example of Java exception handling, where a FileNotFoundException is handled using a try-catch statement:
public class FileExceptionExample {
public static void main(String args[]) {
try {
java.io.FileReader file = new java.io.FileReader("nonexistentfile.txt");
} catch (java.io.FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
// rest of the program
System.out.println("Program continues...");
}
}
Output:
File not found: nonexistentfile.txt
Program continues...
In the above example, a FileNotFoundException is raised when trying to open a file that doesn’t exist. The exception is caught by the catch block, and the error message is printed. After handling the exception, the program continues and prints “Program continues…”.
Now that we have covered how to handle exceptions in Java, let’s explore how to handle exceptions in Python.
Exception handling in Python is similar to handling exceptions in Java. The core concept of exceptions remains the same. It allows you to handle unexpected or unwanted errors gracefully, preventing the program from crashing or terminating unexpectedly.
When an unexpected condition occurs, Python creates an exception object that consists of information about the type, message, and location in the program. The programmer must add an exception handler in the code; if the handler is found, the exception is processed; otherwise, Python’s default exception handler prints the details of the error and terminates the program.
Python organizes exceptions with a base class called BaseException, from which other exception classes inherit. This hierarchy allows developers to handle exceptions more from generic or specific as needed.
The BaseException class is at the top of Python’s exception hierarchy and includes common methods like __str__ and __repr__ that all exceptions can use. However, it is not recommended to use BaseException directly in code because it is too general and can catch all exceptions, including critical ones like system exit or keyboard interruption. Instead, more specific exception classes that are subclasses of BaseException should be used.
Python provides many built-in exception classes, and custom exception classes can also be created as needed.
Python Exception Hierarchy:
Here’s an overview of the hierarchy in Python exception classes:

Here are some common exceptions in Python with the errors that cause them:
Common exceptions include:
Common exceptions include:
Common exceptions include:
Below is an example of a custom exception for handling multiple exceptions in Python:
class CustomError(Exception):
pass
class ValueTooSmallError(Exception):
def __init__(self, message="Value is too small"):
self.message = message
super().__init__(self.message)
All of these exceptions can be caught and handled using try-except blocks, and you can specify multiple exception handlers:
try:
# Some code that might raise exceptions
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except TypeError as e:
print(f"Type error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("No exceptions occurred!")
finally:
print("This will always execute")
Python provides several keywords for exception handling to manage errors or unexpected situations that occur during the execution of a program.
| Keyword | Description |
|---|---|
| try | It encloses code where exceptions might occur and monitors potential error-producing areas. |
| except | It catches and handles exceptions from the try block. It can also handle multiple exception types and store the error in a variable. |
| else | It runs code only when no exception occurs in the try block. |
| finally | It runs even after return statements and executes cleanup code regardless of whether an exception occurred. |
| raise | It can create custom exceptions or re-raise caught exceptions |
| assert | It is used to validate conditions and raises AssertionError if False. |
Here’s an example of how to handle a FileNotFoundError in Python. This occurs when attempting to open a file that doesn’t exist. The exception is raised and can be caught using a try-except block.
try:
# code that may raise an exception
file = open("nonexistentfile.txt", "r")
except FileNotFoundError as e:
print(f"File not found: {e}")
# rest of the program
print("Program continues...")
Output:
File not found: [Errno 2] No such file or directory: 'nonexistentfile.txt'
Program continues...
In the above example, if the file does not exist, Python raises a FileNotFoundError. This error is caught by the except block, and an error message is printed. After handling the exception, the program continues its execution, as indicated by the message “Program continues…”.
Catching and raising exceptions in Python involves using a try-except block to handle errors and the raise keyword to generate exceptions manually.
Let’s understand catching exceptions and raising exceptions in detail.
Catching Exceptions: To catch exceptions, Python uses the try, except, and finally blocks. The code that could cause an exception is placed in the try block, while the except block handles the error. The finally block always executes, whether an exception occurs or not, to clean up the actions.
person = {"name": "Tahneet", "age": 23}
try:
print(person["address"])
except KeyError:
print("Key not found in the dictionary")
finally:
print("This will always run.")
Output:
Key not found in the dictionary
This will always run.
Raising Exceptions: In Python, the keyword raise is used to raise an exception manually. This is useful when you want to enforce specific error handling or trigger custom exceptions for application-specific scenarios.
try:
raise ValueError("Invalid value")
except ValueError as v:
print(v)
Output:
Invalid value
Catching and raising exceptions in Python helps control error management and ensures that the program continues running smoothly. Proper exception handling in Java, Python, or any language helps manage unexpected scenarios and prevent crashes.
Exception handling is crucial for writing robust code. Java and Python are programming languages that also enable the writing of test scripts. Both languages offer built-in exceptions, which make it easier for developers and QA engineers to detect, catch, and resolve errors.
Having exception handling from a testing perspective provides more confidence in the quality and reliability of the application as well.
When it comes to testing, test automation is performed on various combinations of browsers and operating systems, making the test code behave differently because of varying browsers and browser versions. The test might throw an exception because of some attributes that are browser-specific and might not be present on other browsers on which the test is being performed. For example, you might encounter NoSuchAttributeException because of property names when using test automation frameworks like Selenium. You can learn more about it through this blog on common Selenium exceptions.
Handling exceptions in Selenium differs based on the programming language being used.
If you are using Python, the exceptions are handled using the try…except block, where the exception classes are imported from the selenium.common.exceptions package. Similarly, in Java, the exceptions are handled using the try-catch statement.
Similar to Selenium exceptions, understanding exception handling in Cypress is equally important when working with the Cypress framework.
Handling exceptions effectively in Selenium and Cypress ensures that your test scripts remain robust and adaptable. However, the true power of exception handling can be realized when combined with a reliable testing platform like TestMu AI.
AI-based test execution and orchestration platforms like TestMu AI offer manual and automated testing across 3000+ browsers and OS combinations. By running your Selenium and Cypress tests across multiple environments, TestMu AI helps you identify browser-specific exceptions that might go undetected while testing at scale.
Exception handling is essential for managing errors and ensuring smooth execution in both Java and Python. Below are the best practices to be followed:
In conclusion, exception handling is crucial in both Java and Python. It helps programs handle unexpected errors that may occur during execution. Instead of causing the program to crash, the errors can be caught and managed properly. This allows the program to continue running or exit in a controlled way. Proper exception handling increases a program’s durability and dependability.
It helps ensure that the program remains functional under various conditions. This makes it easier for developers to maintain and debug the code because they can quickly identify and fix problems. It also makes the program easier to maintain, as developers can quickly understand and fix any issues.
Did you find this page helpful?
More Related Hubs
TestMu AI forEnterprise
Get access to solutions built on Enterprise
grade security, privacy, & compliance