Error handling

Errors, unfortunately, are very common, inevitable even. Errors detected at runtime are called exceptions, and are fatal, meaning that the execution of the program comes to a halt. However, it is possible to handle exceptions using try statements.

def divide(left,right):
    return left / right

try:
    print(1 / 0)
except ZeroDivisionError:
    print("Cannot divide by 0")
except ValueError:
    print("The integer is too big to be represented")

The code in the try clause will run and it an exception is thrown it will be passed to the except clause if the exceptions matches the one defined. If not then the exceptions will be passed on to any outer try statements or cause the program to halt.

try statements can have multiple except clauses that will be matched sequentially, starting from the first. All exceptions inherit from the Exception class, so in the example below the first except clause will run, even though it’s a ZeroDivisionError that was thrown.

def divide(left,right):
    return left / right
try:
    print(1 / 0)
except Exception:
    print("Something went wrong")
except ZeroDivisionError:
    print("Cannot divide by 0")

try statements may have an else clause that runs if none of the exceptions were matched.

def divide(left,right):
    return left / right
try:
    print(1 / 0)
except ZeroDivisionError:
    print("Cannot divide by 0")
else:
    print("An unknown error occurred")

The error can be captured using as, in case you may want to access it’s properties or use it any other way.

def divide(left,right):
    return left / right
try:
    print(20 / 0)
except ZeroDivisionError as err:
    print("Runtime error: ", err)

Custom errors

You can use the raise keyword to raise your own errors. The error should inherit from the BaseException class.