Error Handling

Error handling is required to ensure that your programs are robust and capable of tackling any issues that may arise.

Keywords

try: - This initiates the block of code that the program will try to run.
except: - This keyword can be followed by an exception type, or if left blank will capture all exceptions. This is followed by a block of code that should be ran if the program raises an exception that matches the exception type stated.
else: - This runs if no errors are raised.
raise: - This keyword allows you to create your own exceptions allowing you to tailor the response your code has to an exception depending on where the program has got to.
finally: - This block of code will run once the try block or the except block has completed.

Example

If we try to run the following code we get an error raised.
a = 3
b = "chair"

c = a / b
Error Raised:
Traceback (most recent call last):
  File "C:/Python3/errors.py", line 4, in <module>
    c = a / b
TypeError: unsupported operand type(s) for /: 'int' and 'str'
We can improve our code to handle this error, by including error handling.
a = 3
b = "chair"

try:
    c = a / b
except:
    print ("Error dividing, please check you have two numbers and try again")
This returns:
Error dividing, please check you have two numbers and try again
This is much better we have created error handling in our code that allows the program to keep running. Though we have captured all errors, if our program was more complicated then we may struggle to debug any errors as these will all be captured. To overcome this we can state which errors we want to capture.
a = 3
b = "chair"

try:
    c = a / b
except TypeError:
    print ("Error dividing, please check you have two numbers and try again")
This returns:
Error dividing, please check you have two numbers and try again
This has allowed us to control the response for the error we are interested in and this will allow other errors to be raised.
a = 3
b = "chair"

try:
    c = a / b
except TypeError:
    print ("Error dividing, please check you have two numbers and try again")
else:
    print ("Else block ran")
finally:
    print ("Final block ran")
This returns:
Error dividing, please check you have two numbers and try again
Final block ran
If we update the initial variables, we can show that when no errors are raised the else block is executed.
a = 3
b = 9

try:
    c = a / b
except TypeError:
    print ("Error dividing, please check you have two numbers and try again")
else:
    print ("Else block ran")
finally:
    print ("Final block ran")
This returns:
Else block ran
Final block ran
Finally, if we wanted to include our own exception, we could include a check that disallows a user to divide by nine.
class ExceptionVariable9(Exception):
    def __init__(self):
        Exception.__init__(self)

a = 3
b = 9

try:
    if b == 9:
        raise ExceptionVariable9()
    c = a / b
    
except ExceptionVariable9:
    print ("Error dividing, You are trying to divide by nine!")
except TypeError:
    print ("Error dividing, please check you have two numbers and try again")
else:
    print ("Else block ran")
finally:
    print ("Final block ran")
This returns:
Error dividing, You are trying to divide by nine!
Final block ran




Related Sections

Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.
Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.


Related Pages

Pickle - The pickle library allows a program to save data in a binary file.
Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines