I'm wondering a user defined exception I've raised in my python program from within a class isn't being handled by the correct exception handler within my main()
. Say I have a class:
class Pdbalog:
# Constructor
def __init__(self, logtype):
if logtype == 1 or logtype == 2:
# These are valid
self.logtypeV = logtype
...<continue processing>
else:
# Invalid
raise Exception("Invalid Logtype")
My main
looks like:
from pdbalog import *
def main():
try:
mylog = Pdbalog(10)
...<other code here>
except "Invalid Logtype":
print('Exiting...')
except:
print('Unhandled exception')
raise
I would expect the when main
is run that the line where I instantiate the Pdbalog
object would raise an exception ( Exception("Invalid Logtype")
) and the exception handler in main ( except "Invalid Logtype"
) would print the output string "Exiting..."
. However, it does not. It is being handled by the unhandled exception handler. What ends up happening is the string "Unhandled exception"
is being output. Why isn't the
except "Invalid Logtype":
handling the exception?
I am using an old version of python (2.4).
Exception("Invalid Logtype")
is still just an Exception
, just now with an error message. "Invalid Logtype"
isn't an error, just a str
, so you can't catch it.
Try:
class InvalidLogtype(Exception): pass
try:
raise InvalidLogType
except InvalidLogType:
pass
Note that you can catch based on error messages by doing
except Exception, e:
if e.args == ("Invalid Logtype",):
...
else:
raise
Try this instead:
class InvalidLogType(Exception):
pass
then
raise InvalidLogType()
then
except InvalidLogType:
etc
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.