newbie question about confusing exception handling in urllib

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Apr 9 11:05:22 EDT 2013


On Tue, 09 Apr 2013 06:19:09 -0700, cabbar wrote:

> How do I
> handle all other exceptions, just say Exception: and handle them? I want
> to silently ignore them.

Please don't. That is normally poor practice, since it simply hides bugs 
in your code.

As a general rule, you should only catch exceptions that you know are 
harmless, and that you can recover from. If you don't know that it's 
harmless, then it's probably a bug, and you should let it raise, so you 
can see the traceback and fix it. In the words of Chris Smith:

    "I find it amusing when novice programmers believe their 
     main job is preventing programs from crashing. ... More 
     experienced programmers realize that correct code is 
     great, code that crashes could use improvement, but 
     incorrect code that doesn’t crash is a horrible nightmare."


One exception to this rule (no pun intended) is that sometimes you want 
to hide the details of unexpected tracebacks from your users. In that 
case, it may be acceptable to wrap your application's main function in a 
try block, catch any unexpected exceptions, log the exception, and then 
quietly exit with a short, non-threatening error message that won't scare 
the civilians:


try:
    main()
except Exception as err:
    log(err)
    print("Sorry, an unexpected error has occurred.")
    print("Please contact support for assistance.")
    sys.exit(-1)


Still want to catch all unexpected errors, and ignore them? If you're 
absolutely sure that this is the right thing to do, then:

try:
    code_goes_here()
except Exception:
    pass

But really, you shouldn't do this.

(For experts only: you *probably* shouldn't do this.)



-- 
Steven



More information about the Python-list mailing list