Selected topic

Error and Exception Handling

Error Handling

Prefer practical output? Use related tools below while reading.

Error vs. Exception

In Python, an error is something that prevents the program from running correctly (e.g., syntax errors). An exception, on the other hand, is a runtime error that occurs when the program attempts to do something invalid (e.g., divide by zero).

Try-Except Block

The try-except block is used to catch and handle exceptions. The basic structure of a try-except block in Python is as follows:
python
try:
    # code to be executed
except ExceptionType:
    # code to handle the exception
Here's an example that uses the ZeroDivisionError exception type:
python
def divide_numbers(a, b):
    try:
        result = a / b
        return result
    except ZeroDivisionError:
        print("Cannot divide by zero!")
        return None

print(divide_numbers(10, 2)) # Output: 5.0
print(divide_numbers(10, 0)) # Output: Cannot divide by zero!


In this example, the divide_numbers function attempts to perform a division operation inside the try block. If the denominator is zero (i.e., a ZeroDivisionError occurs), the except block catches the exception and prints an error message before returning None.

Multiple Exception Types


A try-except block can catch multiple exception types by listing them out in separate except blocks, separated by commas:
python
try:
# code to be executed
except (TypeError, ZeroDivisionError):
# code to handle the exceptions

Here's an example that catches both TypeError and ZeroDivisionError:
python
def divide_numbers(a, b):
try:
result = a / b
return result
except (TypeError, ZeroDivisionError):
print("Invalid input or division by zero!")
return None

print(divide_numbers(10, 2)) # Output: 5.0
print(divide_numbers(10, 'a')) # Output: Invalid input or division by zero!
print(divide_numbers(10, 0)) # Output: Invalid input or division by zero!


In this example, if either a TypeError or a ZeroDivisionError occurs during the execution of the try block, the except block catches the exception and prints an error message before returning None.

Finally Block


A finally block is used to execute code regardless of whether an exception occurred in the try-except block. The basic structure of a try-finally block in Python is as follows:
python
try:
# code to be executed
finally:
# code to be executed always

Here's an example that uses a finally block:
python
def divide_numbers(a, b):
try:
result = a / b
return result
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
finally:
print("Cleanup code executed!")

print(divide_numbers(10, 2)) # Output: Cleanup code executed!
5.0
print(divide_numbers(10, 0)) # Output: Cannot divide by zero! Cleanup code executed!


In this example, the finally block executes regardless of whether a ZeroDivisionError occurs during the execution of the try-except block.

I hope these examples help illustrate the basics of error handling in Python!