Exception handling....dumb question?

K

kbperry

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?
 
F

Felipe Almeida Lessa

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?
.... print 1/0
.... except Exception, e:
.... print '*', e.__class__, '*'
.... print '*', e, '*'
....
* exceptions.ZeroDivisionError *
* integer division or modulo by zero *
 
R

Rune Strand

kbperry said:
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( )
 
T

Trent Mick

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

try:
some code that might blow up

except:
print "some error message"
... 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:
... 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
 
K

kbperry

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.
 
B

Ben Finney

kbperry said:
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>
 
P

Peter Hansen

kbperry said:
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
 
F

Flexx

Ben said:
> 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)
 
F

Felipe Almeida Lessa

Em Dom, 2006-04-02 às 15:54 +0300, Flexx escreveu:
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!"):
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
-1

But this function won't catch exceptions if you don't give it numbers:
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,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top