Error Handling and Exceptions 🚨: Making Python Robust

Intermediate

Robust programs anticipate and manage errors gracefully using exception handling.

Try-Except Block:

try:
    result = 10 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')

You can catch multiple exceptions:

try:
    value = int(input('Enter a number: '))
except ValueError:
    print('Invalid input!')

Finally Block: Executes cleanup code:

try:
    file = open('data.txt', 'r')
finally:
    file.close()

Raising Exceptions:

def validate_age(age):
    if age < 0:
        raise ValueError('Age cannot be negative')

Proper error handling ensures predictable and user-friendly software behavior.