try...except...else...finally
Like many languages, Python provides functionality for catching errors using a try...except
block. Java, for example, has try...catch
which operates in a similar way, but Python goes beyond other languages by providing extra blocks.
Basic exception handling
Let’s have a quick run through how exception catching works in Python.
x = 0
# x = 10
try:
y = 100 / x
except ZeroDivisionError:
y = 0
except Exception as e:
print(e)
This is your standard try...except
block. If we set x
to zero, the dividing by it will throw an exception, which we can catch and use to set y
.
⚠️ This is poor coding, as the more Pythonic way to do this would be to check the value of
x
first, rather than usingtry...except
. Exception catching is more “expensive” than a basic if statement. It works well for example purposes though.
ℹ️ We can have as many
except
statements as we like, catching different errors. CatchingException
catches any error, can can be a little dangerous as the code then “swallows” all errors, which is not usually what you want because it can hide issues that could be fixed if they were visible.
Using else
else:
y += 10
This is where Python starts to offer a little more functionality than other languages. The else
block will execute if no exceptions are found. So if from the first block we uncomment x = 10
, then y
becomes first 10, does not throw an error, and then hits the else
block where it is incremented by 10, so the value of y
becomes 20.
If x
remains initialised as zero, then y
is also set to zero in the exception block, and the else
block is not called.
Using finally
finally:
z = (x, y)
The finally
block is then implemented regardless of whether an exception is thrown or not. In this case, we create a co-ordinate pair z
from the values of x
and y
.
So for x == 0
:
x = 0
try:
y = 100 / 0
except ZeroDivisionError:
y = 0
else:
# Not executed
finally:
z = (0, 0)`
Giving us final co-ordinates of z == (0, 0)
While for x == 10
:
x = 10
try:
y = 100 / 10 # => y == 10
except:
# Not executed as no error
else:
y += 10 # => y == 20
finally:
z = (10, 20)
Giving us final co-ordinates of z == (10, 20)