Alex Rivera | Logout

Raising an exception vs printing?

Asked 2010-01-27T11:59:15.447
19

Whats the difference between raising an exception and simply printing an error.

For example, whats the benefit of using the following:

if size < 0:
        raise ValueError('number must be non-negative')

instead of simply:

if size < 0:
        print 'number must be non-negative'

I'm a newbie, please take it easy on me. :)

Edit
Report

2 Answers

14

Raising an error halts the entire program at that point (unless the exception is caught), whereas printing the message just writes something to stdout -- the output might be piped to another tool, or someone might not be running your application from the command line, and the print output may never be seen.

For example, what if your code is like:

if size < 0:
    print 'size must be non-negative'
else:
    print size * 4

and I call your script like:

yours.py number_source.txt | sum_all_lines.sh

If yours.py outputs plain text in between numbers, then maybe my sum_all_lines.sh will fail because it was expecting all numbers. However, if yours.py quits due to an exception, then sum_all_lines.sh will not finish, and it will be clear to me why the sum failed.

Of course, that's just one example, and your particular case may be completely different.

answered 2010-01-27T12:04:23.397
3

The key difference is whether or not the program will continue to run after your error checking.

For this case:

if size < 0:
    print 'number must be non-negative'

This will just print the message to standard output and the program will continue past your check. So if at some point later in your code you uses size and it is less that 0 you may get an error.

For the other case:

if size < 0:
    raise ValueError('number must be non-negative'

In this case the program will not continue past your check, an exception will be raised. If it is not handled then the entire program will terminate.

Most of the time you will want to raise an exception and have an outer exception handler that catches the exception and tells the use about the error and if possible allows them to re-enter the input.

answered 2010-01-27T12:11:04.333

Your Answer