When things go wrong at runtime
A syntax error means Python could not read your code at all. A runtime error happens while the code runs:
ValueError—int("abc"): the text is not a numberTypeError—"5" + 5: mixing text and numbersZeroDivisionError— dividing by zero
Handling them yourself
try runs the risky lines; if one fails, except catches that error instead of crashing the program.
answer = "42"
try:
number = int(answer)
print(number + 8)
except ValueError:
print("That was not a number")
Catch the error you expect rather than everything, and wrap only the lines that can fail — that keeps the rest of your program honest about real bugs.
else and finally
else runs when nothing went wrong; finally runs either way, which is where cleanup belongs.
try:
value = int("7")
except ValueError:
print("Bad input")
else:
print(value * 2) # 14