try/except

The try/except construct allows you to handle the errors within and fall back on alternative code if something goes wrong. You can use it for an exception as an umbrella case (any error), or specify precise exceptions to catch. In the following code, we're trying to run a bad code, dividing by zero. In this case, Python raises a specific exception—ZeroDivisionError. Knowing that, we add an except ZeroDivisionError clause, printing a string in it:

>>> try:
>>> result = 1 / 0
>>> except ZeroDivisionError:
>>> print('something is wrong!')
something is wrong!

Because we are catching specific ZeroDivisionError exceptions, everything else will still raise an exception. As it is precisely the exception that was raised, we caught it, a print statement was executed, and the code continued the execution. If necessary, we can specify multiple types of errors, use caught exceptions in our code, and even add different behavior for a different type of issue.

Let's illustrate this with another example, using a built-in example for warnings. Warnings are a more explicit way to catch attention, as opposed to printing, and won't halt the code, as exceptions do. In the following code, we define a function that calculates the percent, taking the value and the total arguments. It handles ZeroDivisionError as the preceding code. In addition, it handles TypeError and KeyError (the latter was added just to illustrate how to pass multiple exceptions in the same statement). Finally, there is a fallback scenario for all other types of exceptions:

import warnings  
# built-in library that helps warning people - similar to exceptions, but won't halt code,
# you can also set up filter for different warning types

def percentage(value, total):
try:
return 100 * (value / total)

except ZeroDivisionError:
warnings.warn('Total cannot be zero!')

except (TypeError, KeyError) as e:
# Keyerror here would never occur - just used it for example
warnings.warn(f"Something with the wrong: {e}")
except Exception as e:
raise Exception(value, total, e)

Let's test it in practice. In the following code, we run a function for a proper set of values, for total equal to 0, and, finally, for two strings. In all cases, a proper exception (or lack thereof) was used:

>>> percentage(1, 10)
10.0

>>> percentage(10, 0)
/Users/philippk/anaconda3/envs/py36/lib/python3.7/site-packages/ipykernel_launcher.py:10: UserWarning: Total cannot be zero!

>>> percentage('Hello', 'world')
/Users/philippk/anaconda3/envs/py36/lib/python3.7/site-packages/ipykernel_launcher.py:14: UserWarning: Something with the wrong: unsupported operand type(s) for /: 'str' and 'str'
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.157.62