[Tutor] Re: catching any exception?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Nov 15 16:57:12 2002


> >>> myException = 'my sample exception'
> >>> try:
> ...   raise myException
> ... except Exception, thisException:
> ...   print 'got (%s, %s)' % (Exception, thisException)
> ...   raise Exception(thisException, 'sql here')
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 2, in ?
> my sample exception
>
> See, "myException" was not caught.  How can I catch all exceptions,
> including the ones that DCOracle defines?

Hi Lance,


A "catchall" kind of try/except should do the trick, even if we use the
deprecated string exceptions:

###
>>> try:
...     raise "Oh no!"
... except:
...     print "Gotcha!"
...
Gotcha!
###


Jeff Shannon mentioned that the 'traceback' module provides a way to
access the exception at this stage:

    http://www.python.org/doc/lib/module-traceback.html

Let's see what happens when a string exception is being handled:

###
>>> try:
...     raise "Oh no!"
... except:
...     print "Gotcha!"
...     traceback.print_exc()
...
Gotcha!
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
Oh no!
###




> For that matter, how can I create an exception that's just like a
> "standard" exception?  I think that's part of the problem.  The string
> type of exception that DCOracle defines doesn't have Exception as a
> parent.

According to the Library documentation, we should try to subclass
'Exception' so that it fits with the rest of the standard exceptions:

    http://www.python.org/doc/lib/module-exceptions.html



Good luck!