On Thu, 22 Apr 2010 16:50:30 -0700, Jimbo wrote: > Hello > > I have a relatively simple question. I want to use a try except in a > function & when an error occurs I want to print the error type name(eg > IOError, OSError etc) do you know how I can do this without specifying > all possible errors, eg having to do this "except (IOError, OSError, > IndexError, ....):" > > try: > > ... some code > > except: > # Here I want to print type of error that occured print errorType
As a general rule, bare excepts are terrible practice and should be avoided. At most, you should write: try: ... except Exception: ... which will allow keyboard interrupts to continue to work correctly. In Python 2.5 or 2.6, you can say: try: ... except Exception, e: print e # prints the exception object print type(e) # prints the type of exception print type(e).__name__ # prints the type's name raise # re-raise the error and get a traceback In Python 2.6 you can also use except Exception as e: and in 3.x you *must* use the "as e" form. > The reason I want to do this is because one of my complex programs is > crashing Perhaps you should aim to make them less complex? *wink* > BUT no python error message is comming up in red when I run it, What do you mean, "crashing"? If you're not getting an exception raised, and a printed traceback, how do you know it is crashing? Do you mean it is dumping core? If so, then a try...except won't save you. > so I cant figure out what error occured? So I think its time I learnt to > print out my own errors & their types The best way to print out errors is: DO ABSOLUTELY NOTHING. Python will automatically print out the errors, unless you suppress them with a try...except. So stop suppressing them and let Python do what it is supposed to do! -- Steven -- http://mail.python.org/mailman/listinfo/python-list