On 26 November 2011 11:41, Steven D'Aprano <[email protected]> wrote: > Hugo Arts wrote: >> >> On Sat, Nov 26, 2011 at 11:16 AM, Karim <[email protected]> wrote: >>> >>> Hello, >>> >>> I want to fire my own exception without having the (useful but ugly in my >>> case) stack trace display. >>> >>> How to modify a Exception type class for that purpose which looks like: >>> >>> classs MyError(Exception): >>> pass >>> >>> Cheers >>> Karim >>> >> >> The stack trace is what happens when an exception is uncaught. You >> don't need to modify it. What you want to do is catch the exception, >> print it, then, depending on whether you can recover from the error, >> possibly do a sys.exit(-1). > > If you can recover from the error, by all means catch the exception. That's > what exceptions are for! > > But otherwise, please think very, very, VERY carefully before printing an > error message and exiting. This is normally the wrong thing to do. > > Stack traces are useful. They show you exactly what has gone wrong, and > where (although sadly not why!). There is very little worse than a "helpful" > programmer who turns a sensible, useful stack trace into a useless, stupid > message: > > "An error has occurred" > > or worse. > > Perhaps the most sensible example I can think of is this: > > > def main(): > # your code goes here... > > > if __name__ == '__main__': > try: > main() > except KeyboardInterupt: > # Not an error, so no need for a stack trace. > print "operation cancelled by user" > sys.exit(1) > > > and that's it. Any other exception is a bug in your code, and so the stack > trace should be printed so the user can report it. > > > -- > Steven > > _______________________________________________ > Tutor maillist - [email protected] > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > Although there's nothing wrong with taking the stack trace and cleaning it up - perhaps dumping it to a logfile, using the Traceback module. Asking your users to send a file (or even automating the process in your except: block is much more user friendly than expecting them to be able to copy and paste from a (potentially hidden, for GUI apps) console. It also ensures you get the entire stack trace, rather than just what they think is useful.
-- Rich "Roadie Rich" Lovely Just because you CAN do something, doesn't necessarily mean you SHOULD. In fact, more often than not, you probably SHOULDN'T. Especially if I suggested it. 10 re-discover BASIC 20 ??? 30 PRINT "Profit" 40 GOTO 10 _______________________________________________ Tutor maillist - [email protected] To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
