August 2019
Beginner
482 pages
12h 56m
English
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