Skip to main content

Managing Exceptions

Exceptions are errors that Python detects during execution of the program. If the interpreter experiences an unusual circumstance, such as attempting to divide a number by 0 or attempting to access a file that does not exist, an exception is created or thrown, telling the user that there is a problem.

When the exception is not detected, the execution flow is interrupted, and the console shows the information associated with the exception so that the developer can solve the problem with the information returned by the exception.

Let’s see a Python code throwing an exception while attempting to divide 1 by 0. We’ll get the following error message if we execute it:

def division(a,b):
return a/b
def calculate():
division(1,0)
calculate()

Sample Output

Traceback (most recent call last):
    File “<stdin>”, line 1, in <module>
    File “<stdin>”, line 2, in calculate
    File “<stdin>”, line 2, in division
ZeroDivisionError: division by zero