469,963 Members | 1,838 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,963 developers. It's quick & easy.

Exception handling....dumb question?

In Python,
When using the default except (like following)

try:
some code that might blow up

except:
print "some error message"
Is there a way to show what error it is throwing?

Like in Java, you can do
catch (Exception e){
System.out.println(e);
}

Or something like that.

Is there an equivalent way to do this in Python?

Apr 1 '06 #1
8 1342
Em Sex, 2006-03-31 *s 15:51 -0800, kbperry escreveu:
Is there a way to show what error it is throwing?

Like in Java, you can do
catch (Exception e){
System.out.println(e);
}

Is there an equivalent way to do this in Python?

try:

.... print 1/0
.... except Exception, e:
.... print '*', e.__class__, '*'
.... print '*', e, '*'
....
* exceptions.ZeroDivisionError *
* integer division or modulo by zero *
--
Felipe.

Apr 1 '06 #2

kbperry wrote:
In Python,
When using the default except (like following)

try:
some code that might blow up

except:
print "some error message"
Is there a way to show what error it is throwing?

Like in Java, you can do
catch (Exception e){
System.out.println(e);
}

Or something like that.

Is there an equivalent way to do this in Python?


see sys.exc_info( )

Apr 1 '06 #3
[kbperry wrote]
In Python,
When using the default except (like following)

try:
some code that might blow up

except:
print "some error message"


try: ... 1/0
... except:
... import traceback
... traceback.print_exc()
...
Traceback (most recent call last):
File "<stdin>", line 2, in ?
ZeroDivisionError: integer division or modulo by zero
Or, if you are using the logging module:
import logging
log = logging.getLogger("myscript")
logging.basicConfig()

try:

... 1/0
... except:
... log.exception("whoa!")
...
ERROR:myscript:whoa!
Traceback (most recent call last):
File "<stdin>", line 2, in ?
ZeroDivisionError: integer division or modulo by zero
Cheers,
Trent

--
Trent Mick
Tr****@ActiveState.com
Apr 1 '06 #4
Thanks guys! I appreciate the help.

I have a Python book, but it didn't mention this at all. I also tried
looking through the online docs to no avail.

Apr 1 '06 #5
"kbperry" <ke***********@gmail.com> writes:
In Python,
When using the default except (like following)

try:
some code that might blow up

except:
print "some error message"


This will catch *every* exception, and throw it away before it gets to
your "print" statement.

This is almost never a good idea. You should catch *specific*
exceptions that you know you can deal with at that point in the code.

import logging
try:
foo = 12 / 0
except ZeroDivisionError, e:
print "You *knew* this was going to happen: '%s'" % e
logging.error(str(e))

This allows all other exceptions to propogate back through the call
stack.

More information on 'try':

<URL:http://docs.python.org/ref/try.html>

--
\ "When we call others dogmatic, what we really object to is |
`\ their holding dogmas that are different from our own." -- |
_o__) Charles Issawi |
Ben Finney

Apr 1 '06 #6
kbperry wrote:
I have a Python book, but it didn't mention this at all. I also tried
looking through the online docs to no avail.


This is covered by the tutorial though, and if you're a Python rookie it
would be a good idea to step your way through most of it soon:

See http://docs.python.org/tut/node10.html for the section on exception
handling.

-Peter

Apr 1 '06 #7
Ben Finney writes:
You should catch *specific* exceptions that you know you can deal with at that point in the code.

import logging
try:
foo = 12 / 0
except ZeroDivisionError, e:
print "You *knew* this was going to happen: '%s'" % e
logging.error(str(e))

This allows all other exceptions to propogate back through the call
stack.


import sys, logging
try:
foo = 12/0
except:
e = str(sys.exc_value)
print "You *knew* this was going to happen: '%s'" % (e)
logging.error(e)
Apr 2 '06 #8
Em Dom, 2006-04-02 *s 15:54 +0300, Flexx escreveu:
Ben Finney writes:
> This allows all other exceptions to propogate back through the call
> stack.


import sys, logging
try:
foo = 12/0
except:
e = str(sys.exc_value)
print "You *knew* this was going to happen: '%s'" % (e)
logging.error(e)


The point (I think) Ben was trying to show is that you should not hide
exceptions from the caller's code unless you expected that exception.
For example:

def percentage(now, total):
"""Returns the percentage of now in total."""
return now * 100.0 / total

Very simple. What if I do "percentage(1, 0)"? The code expected me to be
clever enough to know that you can't make a percentage when the total is
zero, so it lets the exception pass by to my code (like: "it's your
problem, not mine!"):
percentage(1, 0) Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 3, in percentage
ZeroDivisionError: float division

But if your function is being used on a context where total can be zero
and it has a meaning, for example, returning -1, then _in_this_case_ you
should catch the exception:

def percentage(now, total):
"""Returns the percentage of now in total.

If total is zero, then return -1.
"""
try:
return now * 100.0 / total
except ZeroDivisionError:
return -1
percentage(1, 0) -1

But this function won't catch exceptions if you don't give it numbers:
percentage(None, 1)

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 7, in percentage
TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

But this is also a problem on the caller's code! You should *not* hide
it from him! But if None is valid in the context of your code, then...
well, you get the point! =)

HTH,

--
Felipe.

Apr 2 '06 #9

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by adi | last post: by
11 posts views Thread by Master of C++ | last post: by
44 posts views Thread by craig | last post: by
5 posts views Thread by Bry | last post: by
1 post views Thread by George2 | last post: by
35 posts views Thread by eliben | last post: by
9 posts views Thread by =?Utf-8?B?UmFq?= | last post: by
1 post views Thread by rainxy | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.