[Tutor] Terminology question

Alan Gauld alan.gauld at btinternet.com
Fri May 15 01:47:30 CEST 2015


On 14/05/15 23:43, Jim Mooney Py3.4.3winXP wrote:
> I noticed that if I call a function that throws an error, I can catch it
> from the caller, instead of catching it in the function. Is this is what is
> known as "errors bubbling up?"

Yes. They can bubble up naturally because there are no handlers lower 
down or you can partially handle it in the function (eg by adding some 
error data to the exception) then call raise to push it up to the next 
level.

> Also, is this how you're supposed to do it?

More or less, except you should aim to deal with errors at the earliest 
opportunity. But bvery often you don;t know the best way to deal with an 
error at the point where it occurs, you need a wider context. So in that 
case bubbling up to a higher level, with a view of the context is the 
right thing to do.


> def get_input():
...
>      try:
>          minimum = int(inps[0])
>          maximum = int(inps[1])
>          rows = int(inps[2])
>          columns = int(inps[3])
>          return minimum, maximum, rows, columns
>      except ValueError as err:
>          print("non-integer entered", err)
>          return None
>      except IndexError as err:
>          print("You didn't enter enough values.", err)
>          return None

Rather than printing the messages you could re-raise
the error but with the error message attached as a string.
Or, more usefully in a function called get_input() force
it to go round a while loop until they provide valid
input.

> vals = get_input()
> if vals:
>      minimum, maximum, rows, columns = vals
>      try:
>          make_table(minimum, maximum, rows, columns)

            make_table(*vals)

would be neater

But it would be better to catch bad input data in the get_input() 
function rather than wait till you use it. It will make debugging easier 
and potentially improve the reliability of the get_input()
in terms of reuse opportunities. After all it's the get_input() 
function's job to get input, so it should check that the inputs
are sane.

So for example you could do some basic checks like ensuring
min <= max, and that rows and cols are non-zero. If not then
either get more inputs or throw a ValueError at that point.
Your try/except then goes round get_input() not the function
that uses the inputs.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list