A program can fail before it starts or while it runs. A syntax error means Python cannot parse the code: for example, if True print("yes") lacks the colon and indentation required for an if statement. Fix the source before running it again. A try inside that invalid file cannot rescue a syntax error that prevents the file from being parsed.
An exception is a signal that an operation could not complete. An unhandled exception stops the current flow and displays a traceback: read its final line for the exception type and message, then follow the file names and line numbers to the operation. Exact traceback formatting varies by Python version.
print("starting")
try:
print(12 / 0)
print("this line is skipped")
except ZeroDivisionError as problem:
print("Could not divide:", problem)
print("continuing")
starting
Could not divide: division by zero
continuing
Python enters try, stops its body at the failing division, and searches for a matching handler. as problem binds the exception so its message can be inspected. After the handler, execution continues after the entire statement. If there is no exception, the handler is skipped. A function called in the try can raise too; the exception travels back to the caller unless it is handled along the way.
call operation → success → continue
↘ exception → matching handler → continue
↘ no match → propagate