Post

Exception Handling - How We Can Display Correct Error Messages To Users

Error handling is all about controlling how the program deals with and handles errors using exceptions. As developers or beginners in coding, one of the first things we do is learn how to read error messages and debug. What happens when an error occurs with a user of the system, not a developer?

Exception Handling - How We Can Display Correct Error Messages To Users

This topic doesn’t need a lot of explanation as its quite straight forward. Exception handling in Python is all about using specified outputs for specific errors. Earlier, I wrote about the different Type Errors that we have in Python and what they mean. Today, we’ll use them in code blocks to specify what the program does when it encounters one of these problems.

On this pass, I learnt that try-except code blocks are used to try and prevent the program from a complete halt over an error, or to provide detailed outputs designed for everyday users.

Think about everyday users of a system, they won’t be able to read something like:

1
2
3
4
5
6
$ python example.py
Enter your age: abc
Traceback (most recent call last):
  File "example.py", line 1, in <module>
    age = int(input("Enter your age: "))
ValueError: invalid literal for int() with base 10: 'abc'

However, they would understand something like this:

1
2
3
$ python example.py
Enter your age: abc
Oops! That’s not a number. Please enter a valid number.

This is where we use exception handling to configure our system to provide better descriptions for errors. By combining Python’s error types with try-except code blocks, we can create programs that better communicate errors to a user of the system. This way, whoever the system is intended for will know how to rectify the error made.

During this post, I will describe the customised output of errors as try, except code blocks and the default error messages as tracebacks.


Try and Except Syntax

This is the basic structure of a try / except block in Python:

1
2
3
4
5
6
7
8
try:
    # Run this code
except [ExceptionType]: # eg ValueError, TypeError, ZeroDivision...
    # Execute this code if an exception occurs in the try
else:
    # Run this if no exceptions in try
finally:
    # Always run this code, regardless of exceptions

In practice, beginners will mostly use just try and except. Key points to take away from try, except are:

  • The try block runs first
  • If an error occurs, Python immediately goes to the except block
  • The program does come to a halt, but with a non-technical explanation as to why.

Example:

1
2
3
4
5
6
try:
    print(10 + '5')
except TypeError:
    print('unable to add a string type to an integer, try again!')
except ValueError:
    print("")

This example demonstrates how, if our program encounters a TypeError, it will give you a specific error message for that, and if a ValueError, something else. At first, I thought that using the try-except function would begin a loop and allow the program to go a step back to revert the error; while you can get the program to do this by placing it in a while loop, it’s not designed for that.


What Exception Handling Is Really For

Exception handling is all about controlling the output for each error, not eradicating errors. We will always have situations from either the user or the developer where something goes wrong in the code or while using it. What we need to have done is control how the error is displayed and what it allows next.

For developers, Python’s default error messages are extremely helpful.
For users, they are often confusing and intimidating.

To keep my learning journal as organised as I could, I’ve decided to split day 17 into 2 posts. One about exception handling and the other going in a little more detail about intermediate tools and patterns available in Python.

Go to day 17 part 2

This post is licensed under CC BY 4.0 by the author.