Chapter 9. Exceptions and Message Boxes: Get the message?

image with no caption

Sometimes things just go wrong. You just need to handle it.

There will always be things beyond your control. Networks will fail. Files will disappear. Smart coders learn how to deal with those kinds of errors and make their programs recover gracefully. The best software keeps the user informed about the bad things that happen and what should be done to recover. By learning how to use exceptions and message boxes, you can take your software to the next level of reliability and quality.

What’s that smell?

Just when it looked like things were going so well, there was a problem in the Head-Ex storeroom.

image with no caption

A trainee was recording the consignment of cheese when there was a problem that prevented the program from recording the delivery. That meant the cheese was never assigned to a delivery truck. So the cheese never left the storeroom and it just sat there for a very long time. And that meant—well, you can just imagine...

To prevent the same thing happening again, you need to find what caused the problem.

Someone changed the file permissions

It turns out the whole thing was caused when someone from Technical Support decided to change the permissions on the deliveries.txt file, making it read-only. When the system tried to write deliveries into the file, it failed. But what’s worse, it failed silently:

image with no caption

When you were writing programs that ran in the Python Shell, you could always tell when it failed: a huge, ugly error message appeared. Why not with GUIs? Don’t they do the same?

They do, but the trouble is that the message appears in the Shell and your user is busy looking at the nice GUI, so the ugly error can often be missed.

Note

To reproduce this error on your PC, you need to make your deliveries.txt file read-only. How you do this depends upon your operating system. If you are unsure how to make a file read-only, check the Web for more advice (or ask a friendly local guru). On most systems, it involves editing the properties of the file.

When using a GUI, how do you spot errors? Once spotted, what happens then?

When it couldn’t write to the file, the program threw an exception

What happens when an error occurs? Some errors are really bad: they cause the program to crash. Other, less serious errors are known as recoverable: the program can keep running, even though something went wrong. You can spot these situations in your code, because most programming technologies throw an exception when they occur.

Imagine a line of code that has a problem, such as the line that was trying to write to the deliveries.txt file. Python will spot that the append operation failed and, instead of running the rest of the code that follows, Python abandons ship and skips out of the code completely. That’s what throwing an exception means: the program doesn’t crash, but it abandons what you were trying to do and tries to recover the situation:

image with no caption

But why skip past the rest of the code? Why not keep on running? Generally, that would be a bad idea. Once a line of code has gone bad, there’s no way of knowing if it makes sense to keep running the code that follows. For example, if the Head-Ex code can’t open the deliveries file to append to it, it makes no sense to continue trying to write data to the unopened file!

In order to recover, you need to start running your code from somewhere else.

Catch the exception

Python spots when an exception is thrown, and you can write some code to run when the exception occurs. This is called catching the exception. The code that you run when there’s an error resulting in the thrown exception is called an exception handler.

image with no caption

A piece of code that runs when an exception is thrown is called an exception handler.

Creating exception handlers can really make life easy for your users. Instead of a flaky program that crashes or fails silently the first time something weird happens, you can write programs that gracefully recover from errors. Exception handlers tidy up when something goes wrong and can even let your user know that something strange happened.

That’s what you need here: an exception handler that tells the user when there’s a problem writing a delivery to the file.

How are exception handlers written in Python?

Watch for exceptions with try/except

In order to recover from an error as it happens, you need to indicate the code that might throw an exception. In Python, you do this with try and except.

All you need to do is take the piece of potentially troublesome code and add the try and except labels:

image with no caption

If an exception is thrown between the try and except labels, the code that follows the except label runs. The code that threw the exception is abandoned. If no exception occurs, the code runs normally and the code that comes after the except label is ignored.

Notice that the try/except labels are wrapped around all of the function’s code. If there’s a problem opening the deliveries.txt file, you don’t ever want to try writing to it. So, when trouble strikes, you should adandon ship and skip to the code that tries to recover from the error.

The code that then runs is the exception handler.

There’s an issue with the exception handler

You do a quick demo for the folks at Head-Ex and, even though the program works, it’s not quite what they need.

image with no caption

The error message is more visible than when it was appearing in the Python Shell, but it isn’t a whole lot more visible. Sure, you’ve proved that you can spot when an error happens and then run an exception handler in order to do something about the error. But you really need to do something that will interrupt the user and highlight the situation. You need something that will force the user to acknowledge the error before he continues doing something else.

A GUI message box might do the trick.

A message box demands attention

Most of the time, GUI programs put the user in charge. If the user chooses to click a button or edit a field, the computer lets them do just that in whatever order and at whatever time the user chooses. But sometimes, GUI programs need to stop the user and ask her a question, getting her to confirm or acknowledge something. That’s where message boxes come in.

A message box is something that requires a response, which is why it’s sometimes called a dialog box.

The simplest message box displays a message with a single OK button:

image with no caption

A message box always displays the message in a separate window, typically in front of your main GUI window. And it won’t go away until you click it, dismissing it. That’s why message boxes are the most commonly used way of displaying errors. The user has to read and respond to the error before continuing.

You should be sparing in how often you display message boxes, because if users see too many of them, they are likely to click them without reading the message. But, when used carefully, they keep your user informed and alert.

Creating message boxes in Python

All of the message box code is contained within a tkinter module called messagebox, so the first thing to do is import the module:

import tkinter.messagebox

Then, you’re good to go. Within the messagebox module, there’s a whole bunch of different dialogs to choose from. But all of them fall into two main categories.

Message boxes that say stuff

To display a simple message on the screen, you might display a message box like this:

image with no caption

Message boxes that ask stuff

If you need a message box that asks the users a question, you will need to check the return value to see what they chose:

image with no caption

When tkinter gets to this line, it will wait for the user to answer the question and then assign True (yes), False (no), or None (cancel) to the response variable.

image with no caption

Let’s see what other message boxes are available.

image with no caption

The error message box was exactly what Head-Ex needed.

By catching exceptions and displaying important information in message boxes, you can greatly improve the experience of your users when things go wrong.

Great work!

Your Programming Toolbox

You’ve got Chapter 9 under your belt. Let’s look back at what you’ve learned in this chapter:

Programming Tools

* Some errors don’t crash your program - they throw exceptions instead.

* You can run code when there’s an exception - this is called “catching the exception.”

* Code that runs because of an exception is called an exception handler.

* GUI message boxes display information and ask questions.

* Message boxes are also known as “dialog boxes.”

* Message boxes require the user to respond, even if it is just to click an OK button.

Python Tools

* You can catch exceptions by using a try/except block.

* “except Exception as ex” will assign the exception message to a variable called “ex”.

* You can display the exception error message by formatting it as a string.

* To display message boxes, you need to import the “tkinter.messagebox” module.

* Message boxes that display information are all called “show...()”.

* Message boxes that ask questions are all called “ask...()”.

* Message boxes return True if the response was OK, Yes, or Retry.

* Message boxes return False if the response was No.

* Message boxes return None if the response was Cancel.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.17.45