error handling

Cameron Laird claird at lairds.us
Thu Aug 10 21:53:54 EDT 2006


In article <1155256055.663368.96000 at 74g2000cwt.googlegroups.com>,
Chris <chrispatton at gmail.com> wrote:
>I want to do this because there are several spots in my program where
>an error might occur that I want to handle the same way, but I don't
>want to rewrite the try..except block again. Is that clearer?
			.
			.
			.
Oh, yes!

I don't like
  
  try:
    fp1 = open("file1")
  except IOError:
    complain("I can't get at file1")
    return
  ...
  try:
    fp2 = open("file2")
  except IOError:
    complain("I can't get at file2")
    return
  ...

nearly as much as 

  def my_open(fn):
    try:
      fp = open(fn)
    except IOError:
      complain("I can't get at %s" % fn)
      return None
    return fp

  fp1 = my_open("file1")
  if fp1:
    ...
  fp2 = my_open("file2")
  if fp2:
    ...

While that's not a good model for all possible meanings of "handle
the same way", I hope you find it suggestive.



More information about the Python-list mailing list