Error Handling

Error handling in Python allows you to gracefully manage exceptions and errors that may occur during the execution of your code.

Exceptions and Errors

In Python, errors and exceptional events are represented by objects called exceptions. Errors can occur due to various reasons such as invalid input, file not found, or division by zero.

For example, a common exception is the ZeroDivisionError which occurs when dividing by zero:

Pythontry:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)
    # Output: Error: division by zero

Understanding and handling exceptions is crucial for writing robust and reliable code.

Try, Except Blocks

The try and except blocks are used to catch and handle exceptions. Code inside the try block is executed, and if an exception occurs, it is caught by the corresponding except block.

Here's an example handling a ValueError:

Pythontry:
    value = int("abc")
except ValueError as e:
    print("Error:", e)
    # Output: Error: invalid literal for int() with base 10: 'abc'

This prevents the program from crashing and allows you to handle errors gracefully.

Handling Types of Exceptions

You can handle different types of exceptions using multiple except blocks or a single except block with multiple exception types:

Pythontry:
    result = 10 / 0
except ZeroDivisionError as e:
    print("Error:", e)
    # Output: Error: division by zero
except ValueError as e:
    print("ValueError:", e)
    # This block won't be executed in this example

Handling specific exception types allows for more fine-grained error management.