How to Handle Exceptions
How can we handle an exception thrown within a python process
We'll cover the following...
Handling exceptions in Python is really easy. Let’s spend some time writing some examples that will cause exceptions. We will start with one of the most common computer science problems: division by zero.
Press + to interact
1 / 0# Traceback (most recent call last):# File "<string>", line 1, in <fragment># ZeroDivisionError: integer division or modulo by zero
If you think back to elementary math class, you will recall that you cannot divide by zero. In Python, this operation will cause an error, as you can see in the first half of the example. To catch the error, we wrap the operation with a try/except statement.
Press + to interact
try:1 / 0except ZeroDivisionError:print("You cannot divide by zero!")# You cannot divide by zero!
Bare Excepts
Here’s another way to catch ...
Access this course and 1400+ top-rated courses and projects.