Mastering Exception Handling in Python: Try, Except, Finally, and Best Practices

1. Introduction: The Importance of Exception Handling in Python

In programming, exceptions and errors are unavoidable. However, by handling exceptions properly, you can prevent unexpected program crashes and provide meaningful error messages to users. Python offers a powerful mechanism to deal with such exceptions. Using exception handling improves the reliability of your program and ensures smoother execution. For example, if a user attempts to divide by zero or open a non-existent file, the program would immediately stop without exception handling. With proper handling, however, the program can continue running or display a clear error message to the user.

2. Exception Handling in Python: Basic Syntax and Flow

In Python, three main keywords are used for exception handling: try, except, and finally.

2.1 Detecting Errors with the try Statement

The try statement is used to enclose code that may raise an error. This typically includes network operations, file handling, or user input—areas where runtime errors are common.
try:
    result = 10 / 0
except:
    print("An error occurred")
In this example, the invalid operation 10 / 0 triggers an exception, and the except block executes.

2.2 Handling Errors with the except Statement

The except statement catches the exception and defines what to do when it occurs. By handling errors properly, you can avoid unexpected program behavior. You can even specify different handlers for different exception types.
try:
    print(a)
except NameError:
    print("Variable is not defined")
except ZeroDivisionError:
    print("Division by zero is not allowed")
This way, you can set individual handling for multiple exceptions.

2.3 Releasing Resources with the finally Statement

The finally block always executes, regardless of whether an exception occurs. It is especially useful for ensuring resources like files or network connections are released properly.
try:
    file = open("test.txt", "r")
finally:
    file.close()
Thus, finally is highly valuable when managing resources such as file operations and database connections.
侍エンジニア塾

3. Common Exceptions and How to Handle Them

Python provides many built-in exceptions. Below are some of the most common ones and how to deal with them.

3.1 NameError: Using an Undefined Variable

A NameError occurs when you reference a variable that has not been defined.
try:
    print(a)
except NameError:
    print("Variable is not defined")

3.2 TypeError: Invalid Operations Between Different Types

A TypeError occurs when an invalid operation is performed between incompatible types, such as adding a number and a string.
try:
    result = '10' + 5
except TypeError:
    print("Attempted invalid operation between different types")

3.3 ValueError: Invalid Values Passed

A ValueError occurs when a function receives an argument of the right type but an inappropriate value, such as trying to convert a non-numeric string to an integer.
try:
    number = int("abc")
except ValueError:
    print("Invalid value provided")

4. Handling Multiple Exceptions

Python allows you to catch multiple exceptions within a single try block. You can either handle them separately or group them together.

4.1 Handling Multiple Exceptions Individually

To handle different exceptions separately, use multiple except blocks.
try:
    result = 10 / 0
except ZeroDivisionError:
    print("Division by zero is not allowed")
except NameError:
    print("Variable is not defined")

4.2 Handling Multiple Exceptions Together

If you want to handle different exceptions with the same code, you can catch them together in one except statement.
try:
    result = 10 / '10'
except (ZeroDivisionError, TypeError):
    print("An invalid operation occurred")
By applying common handling for different exceptions, you can keep your code concise.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

5. User-Defined Exceptions and the raise Statement

Python also allows you to define custom exceptions for special cases not covered by standard exceptions. These custom exceptions can be raised deliberately using the raise statement.

5.1 Raising Custom Exceptions with raise

For example, you can create a custom error for cases where negative values are not allowed.
def check_value(value):
    if value < 0:
        raise ValueError("Negative values are not allowed")
    return value

try:
    check_value(-10)
except ValueError as e:
    print(e)
With raise, you can control error generation and display meaningful error messages.

6. Summary and Best Practices

Exception handling is essential for making Python programs more robust and secure. Here are some best practices to follow:
  • Catch specific exceptions: Always catch the most specific error type possible instead of overusing generic Exception. This ensures better error management.
  • Manage resources properly: Always release resources like files or network connections in a finally block.
  • Provide clear error messages: When displaying error messages to users, make them clear, informative, and actionable.
By implementing proper exception handling, you can improve your program’s reliability and write code that continues running smoothly even when errors occur, without frustrating the user.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール