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.
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 failuresexcept ValueError as e— catch a type and inspect itexcept (A, B)— catch several types at onceelse:— run only if no errorfinally:— always run (cleanup)raise— re-raise or signal an error
Official documentation: Python Tutorial: Handling Exceptions