In this tutorial, we will provide you with an example of exception handling in Python. For simplicity, we will work with the division function. Let’s start with a simple version.
def div_func(a,b): return a/b print(div_func(10,2))
5.0
The function seems to work correctly. But let’s see what we get when we ask to divide by 0.
print(div_func(10,0))

As we can see, we get the above error. Using the try-except
statement, we can handle these errors. Let’s say that we want to return the message “You cannot divide by 0”.
def div_func(a,b): try: return a/b except: return "You cannot divide by 0" print(div_func(10,0))
You cannot divide by 0
print(div_func(7,2))
3.5
As we can see, we managed to “handle this error”, but we took it for granted that the error was the division by zero. The good news is that we can use the base class Exception that is used for all exceptions that are written within Python. We can return the exception message by using the “as e” after the exception, which acts as an alias for the exception.
def div_func(a,b): try: return a/b except Exception as e: return e print(div_func(10,0))
division by zero
As we can see, we returned the error detected by the class “Exception”. We can also get access to the error type using the e.__class__
.
def div_func(a,b): try: return a/b except Exception as e: return e.__class__ print(div_func(10,0))
<class 'ZeroDivisionError'>
Let’s see another example, where we ask to divide by string, in this case with the “two“.
def div_func(a,b): try: return a/b except Exception as e: return e print(div_func(10,"two"))
unsupported operand type(s) for /: 'int' and 'str'
If we know the expected error, we can define it in the except
statement. For example:
def div_func(a,b): try: return a/b except ZeroDivisionError as e: return e print(div_func(10,0))
division by zero
Finally, it is important to know, that we can handle more than one exception. For example:
def div_func(a,b): try: return a/b except ZeroDivisionError as e: return e except Exception as e: return e print(div_func(10,"5"))
unsupported operand type(s) for /: 'int' and 'str'
Raise an Exception
We can raise an exception if a condition occurs. For example:
x = 101 if x >= 100: raise Exception("All numbers must be less than 100")
This exception will stop the program.