Python · errors

Try-Except

Catch errors as they happen, so one bad value doesn't crash the whole program.

Basic try-except


        # catch any exception
        try:
            result = 10 / 0
        except:
            print("Error occurred")
        # ans: Error occurred
      

When a line raises an error, Python abandons the rest of the try block and jumps to except.

Specific exception


        # catch a specific exception
        try:
            result = 10 / 0
        except ZeroDivisionError:
            print("Cannot divide by zero")
        # ans: Cannot divide by zero
      

The exception object


        # access exception details
        try:
            result = 10 / 0
        except ZeroDivisionError as e:
            print(f"Error: {e}")
        # ans: Error: division by zero
      

as e names the exception object; printing it shows its message.

Multiple except blocks


        # handle different exceptions
        try:
            value = int(input())
            result = 10 / value
        except ValueError:
            print("Invalid number")
        except ZeroDivisionError:
            print("Cannot divide by zero")
        # ans: no error: result is 2.0
      
the user types

Catch multiple exceptions


        # one handler for several types
        try:
            # code
            pass
        except (ValueError, TypeError):
            print("Type or value error")
      

A tuple of exception types: the handler runs if the error is any one of them.

Try-except-else


        # else runs if there was no exception
        try:
            result = 10 / 2
        except ZeroDivisionError:
            print("Error")
        else:
            print("Success")
        # ans: Success
      

Try-except-finally


        # finally always runs
        try:
            file = open("data.txt")
        except FileNotFoundError:
            print("File not found")
        finally:
            print("Cleanup")
        # ans: File not found, then Cleanup
      
data.txt

All four together


        # the full shape
        text = "42"
        try:
            x = int(text)
        except ValueError:
            print("bad")
        else:
            print("ok", x)
        finally:
            print("done")
        # ans: ok 42, done
      
text =

try → except or else → finally.

Exercises

Predict what happens, then press → to trace.

Exercise 1


        # catch all exceptions?
        try:
            x = 1 / 0
        except:
            pass
        # ans: catches everything (not recommended)
      

Exercise 2


        # what is e?
        try:
            x = 1 / 0
        except ZeroDivisionError as e:
            type(e)
        # ans: <class 'ZeroDivisionError'> (e is a ZeroDivisionError instance)
      

Exercise 3


        # when does else run?
        try:
            x = 5
        except:
            print("Error")
        else:
            print("OK")
        # ans: "OK" (no exception)
      

Exercise 4


        # finally with return?
        def func():
            try:
                return 1
            finally:
                print("Finally")
        func()
        # ans: prints "Finally", then returns 1
      

Exercise 5


        # nested try?
        try:
            try:
                x = 1 / 0
            except ValueError:
                pass
        except ZeroDivisionError:
            print("Caught")
        # ans: "Caught"
      

An error the inner try doesn't handle travels outwards to the next try.

Exercise 6


        # multiple except order?
        try:
            x = 1 / 0
        except Exception:
            print("General")
        except ZeroDivisionError:
            print("Specific")
        # ans: "General" (the first matching handler wins)
      

Put specific exceptions before general ones.

Exercise 7


        # finally without except?
        try:
            x = 5
        finally:
            print("Done")
        # ans: valid, prints "Done"
      

Exercise 8


        # else without except?
        try:
            x = 5
        else:
            print("OK")
        # ans: SyntaxError (else needs an except)
      

Exercise 9


        # exception in finally?
        try:
            x = 5
        finally:
            y = 1 / 0
        # ans: raises ZeroDivisionError
      

Exercise 10


        # bare except position?
        try:
            x = 1 / 0
        except ValueError:
            pass
        except:
            print("Other")
        # ans: "Other"
      

Remember

try

Stops at the first error and jumps to a handler.

except

Handlers are checked in order; the first that matches runs. A bare except catches everything.

else

Runs only when the try block raised nothing.

finally

Always runs: after success, after a handled error, even before a return.