Exception handling
When you suspect that the code may raise an exception, you should use the try: problematic_code except
code block to surround the "problematic" piece of code. In effect, when the exception is raised, execution is not terminated, but the code following the except
clause will try to handle the problem in an elegant way.
Let's look at typical try ... except statement.
try:
print(int('a'))
except ValueError:
print('You tried to do a nasty thing...')
Whenever you try to convert letter 'a' to an integer value, you'll spot an exception. In the case where you get data from an external source (console, file, etc.) you should not trust the data types, so it’s wise to surround the fragile code (int()
in this example) with a try... except block.