Syntax to catch specific exceptions ?

Joonas Paalasmaa joonas at olen.to
Sun Mar 10 17:21:13 EST 2002


Pekka Niiranen wrote:
> 
> I am trying to find correct python syntax and structure for the
> following exceptions
> ------------------------
> mypath = os.path.join(os.getcwd(), 'mydirectory', 'mysettings.pxp')
> try:
>         f = open(mypath, "r")
> 
> except "mydirectory does not exists":
>         try:
>                 create_mydirectory_for_the_next_read()
>                 save_default_values(mypath)
>         except "no permission to create mydirectory":
>                 do_whatever()
> 
> except "no permission to enter mydirectory":
>         print "whatever1"
>         use_defaults()
> 
> except "file mysettings.pxp does not exist":
>         print "whatever2"
>         use_defaults()
> 
> except "no permission to open mysettings.pxp":
>         print "whatever3"
>         use_defaults()
> 
> -------------------------
> 
> I can get the error text and number as follows, but how to catch only
> "File exists" OSError ?
> 
> try:
> ...  os.mkdir('e:\\tmp')
> except OSError, (errno, strerror):
> ...  print strerror
> ...
> File exists

How about catching all exceptions and then examining the traceback?

- Joonas



More information about the Python-list mailing list