Gracefully handling errors with try and catch exceptions in Python

By Abhinash Jena on January 28, 2025

Handling errors is the process of anticipating, detecting, and resolving errors or exceptions that may occur during the execution of a program. By using error-handling methods, programmers ensure that the program continues to run smoothly even when they occur.

TIP

Without proper error handling, a program may crash when it encounters an unexpected situation, such as dividing by zero.

denominator = float(input("Enter a denominator: ")) 
print(10/denominator)
print("Execution finished successfully!")
Enter a denominator: 0
ZeroDivisionError: float division by zero

When the input is 0, the code will attempt to divide 10 by zero, leading to ZeroDivisionError. This will cause the program to crash abruptly and not execute the rest.

When errors are properly handled, it becomes easier to identify and fix bugs in the code. Error messages can provide valuable information about the nature and location of the problem, making the debugging process more efficient. In Python, error handling is done using the try and except blocks. It helps to catch and handle exceptions (errors) that may occur during the execution of a code and prevent it from crashing.

denominator = float(input("Enter a denominator: "))

try:

  print(10/denominator)

except ZeroDivisionError:

  print("Error: You cannot divide by zero.")

print("Execution finished successfully!")
Enter a denominator: 0
Error: You cannot divide by zero.
Execution finished successfully!
  • The try block: Contains the code that might raise an exception (in the above case, the division by denominator) and is placed inside the try block.
  • The except block: When an error occurs while executing the try block, the execution leaves the code in the try block and executes code inside the except block.
TIP

If no error occurs in the try block, the code in the except block is skipped, and the program continues to the next line after the try-except structure.

The try-except structure provides a way to print helpful error messages to the user instead of exiting the program. Furthermore, the except block can also contain complex programs to like event triggers such as emails. Using try-except makes the code more robust and helps to handle a wider range of scenarios.

Handling files with try and catch exception

Using try and except ensures that the program continues to run smoothly even if an error occurs. Working with files can often lead to runtime errors when something goes wrong.

EXAMPLE

The file doesn’t exist, permissions are restricted, or the file is corrupted.

Different file operations can raise different types of errors like:

  • FileNotFoundError occurs when trying to open or access a file that does not exist.
try: 

  with open("file.txt", "r") as file:

    content = file.read()

except FileNotFoundError:

  print("File not found.")
  • PermissionError occurs when trying to access a file without the necessary permissions.
  • IsADirectoryError occurs when trying to open a directory as if it were a file.
  • FileExistsError occurs when trying to create a file that already exists.
  • IOError or OSError is a general error for input/output operations, such as disk full, device not ready, or other system-related issues.
  • UnsupportedOperation occurs when performing an operation that is not supported by the file mode.
  • ValueError occurs when passing an invalid argument to a file operation.
  • AttributeError occurs when trying to use a file object method that doesn’t exist.
  • TypeError occurs when passing an invalid type to a file operation.
  • RuntimeError occurs when the file operation fails due to runtime issues

Exception handling with try and except ensures that file handling errors are handled gracefully without crashing the program. Below are some of the practices that a robust programmer should incorporate especially while working with files.

  • Always use try-except blocks to handle potential errors.
  • Use with statement to ensure files are properly closed.
  • Check file existence and permissions before performing operations.
  • Specify the correct file mode and encoding.
  • Handle exceptions gracefully and provide meaningful error messages.

Handling errors with except Exception as e

In Python, the except Exception as e construct is a powerful way to catch and handle any exception that occurs in the code. This is particularly useful when handling unexpected errors gracefully or to log errors for debugging.

try:

  # Code that might raise an exception

  operation()

except Exception as e:

  # Handle the exception

  print(f"An error occurred: {e}")
An error occurred: name 'operation' is not defined

The Exception in except Exception as e is the base class for all built-in exceptions in Python. The as e part assigns the exception object to the variable e, to access details like error message, type, etc. Furthermore, except Exception as e can also be combined with specific exception handling.

try: 

  with open("file.txt", "r") as file:

    content = file.read()

  result = 10 / 0

except FileNotFoundError as e:

  print(f"File not found: {e}")

except ZeroDivisionError as e:

  print(f"Division by zero: {e}")

except Exception as e:

  print(f"An unexpected error occurred: {e}")

Although the except Exception as e method offers flexibility to handle different types of errors in a single except block but because of its overly broad nature, it can also catch unintended exceptions, masking bugs. This method also doesn’t differentiate between different types of errors, making debugging harder. If this method is not properly handled it can silently ignore critical errors. Below are the best practices while implementing this method.

  • Use specific exception types like FileNotFoundError or ZeroDivisionError, whenever possible.
  • Error logs help to critically investigate problems in a code. So, log the exception details for debugging.
  • Never use a bare except or without specifying Exception, as it can catch system-exiting exceptions like KeyboardInterrupt and SystemExit.
  • Use a finally block for cleanup operations like closing files or releasing resources.
try: 

  file = open("file.txt", "r")

  content = file.read()

except Exception as e:

  print(f"An error occurred: {e}")

finally:

  file.close() # Ensure the file is always closed

Challenge: Can you code?

Develop a program to manage student scores. The program should enable users to:

  • Add student scores.
  • View all stored scores.
  • Calculate the average score.
  • Save scores to a file.
  • Load scores from a file.

This task will require the use of conditional statements, functions, loops, file handling, error handling, and Python built-in functions.

Menu

The program should repeatedly show a menu with the following options:

  1. Add a student score.
  2. View all scores.
  3. Calculate the average score.
  4. Save scores to a file.
  5. Load scores from a file.
  6. Exit the program.

Use a while loop to repeatedly display the menu and process user input.

Functions

Create separate functions for each menu option like add_grade(), view_grades(), etc.

Data

Use a dictionary to store student scores scores = {}.

Error handling

Check if grades are between 0 and 100. Use try and except for file operations and input validation.

NOTES

I am an interdisciplinary educator, researcher, and technologist with over a decade of experience in applied coding, educational design, and research mentorship in fields spanning management, marketing, behavioral science, machine learning, and natural language processing. I specialize in simplifying complex topics such as sentiment analysis, adaptive assessments and data visualizatiion. My training approach emphasizes real-world application, clear interpretation of results and the integration of data mining, processing, and modeling techniques to drive informed strategies across academic and industry domains.

Discuss