on the importance of exceptions

Meredith Montgomery mmontgomery at levado.to
Mon Sep 5 18:59:28 EDT 2022


I'm trying to show people that exceptions are a very nice thing to have
when it comes to detecting when something went awry somewhere.  I'd like
a real-world case, though.  

Here's what I'm sort of coming up with --- given my limited experience
and imagination.  Below, you have f calling g caling h calling j which
returns True or False based on a random thing.  (This simulates a task
that sometimes succeeds and sometimes fails.)  If while at f() I want to
know what happened at j(), I'm going to have to propagate that
information upwards through the execution stack.  I can't do that right
now: I'd have to change f, g and h.

--8<---------------cut here---------------start------------->8---
from random import randint
  
def f():
  g()

def g():
  h()

def h():
  if j():
    print("I got a 2.")
  else:
    print("I got a 1.")

def j():
  return randint(1,2) == 2
--8<---------------cut here---------------end--------------->8---

If instead of that, j() would be raising an exception when it fails,
then all I only need to change f() to know what happens.

I could replace j's test with opening a file, say.  That would improve
it a little.  I'm sure you guys know excellent cases to show.  Would you
be so kind to share anything you might have in mind?


More information about the Python-list mailing list