← Python Programming
Files, errors and data · 15 MIN

Exceptions and error handling

Exceptions and error handling

Exceptions represent errors during execution. Use try and except to handle specific expected exceptions, else for the success path and finally for cleanup. Avoid catching every exception without logging or a clear recovery plan.

Try it yourself

Change the example, run it, and explain the result in your own words. Then create one variation of your own.

Key idea

Use the example as a starting point, not something to memorize. Practise, inspect the result and make small improvements.

Code example

try:
    number = int(input("Enter a number: "))
except ValueError:
    print("Please enter a whole number.")
else:
    print(number * 2)