try / except

A block that runs risky code and catches exceptions instead of crashing.

try / except is how Python handles exceptions. Code that might fail goes in the try block; if it raises an error, the matching except block runs instead of the program crashing. Add else for code to run when nothing failed, and finally for cleanup that always runs.

Example
input_value = "oops"
try:
    age = int(input_value)     # raises ValueError
except ValueError:
    age = 0                    # handle it
finally:
    print("done")              # always runs
print(age)
Output
done
0

Where this shows up in real Python

You will wrap file reads, network calls, and type conversions in try/except so one bad input does not take down the whole script.

try / except tools

  • try: / except: — run risky code and catch failures
  • except ValueError as e — catch a type and inspect it
  • except (A, B) — catch several types at once
  • else: — run only if no error
  • finally: — always run (cleanup)
  • raise — re-raise or signal an error

Official documentation: Python Tutorial: Handling Exceptions

Related lessons