try, except, else and finally
except catches specific errors, so list the types you expect and avoid a bare except. else runs only when no error happened and finally always runs, which is ideal for clean up. You can catch several types in one except using a tuple.
Example
def parse(text):
try:
number = int(text)
except ValueError:
print("not a number")
else:
print("parsed", number)
finally:
print("done with", repr(text))
parse("42")
parse("abc")Result
parsed 42 done with '42' not a number done with 'abc'
Exercise
Which block always runs?
try: pass except Exception: pass : print("always")
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.