Should I always specify an exception type in `except` statements?

前端 未结 7 1108
广开言路
广开言路 2020-11-22 15:33

When using PyCharm IDE the use of except: without an exception type triggers a reminder from the IDE that this exception clause is Too broad.

相关标签:
7条回答
  • 2020-11-22 15:52

    You should not be ignoring the advice that the interpreter gives you.

    From the PEP-8 Style Guide for Python :

    When catching exceptions, mention specific exceptions whenever possible instead of using a bare except: clause.

    For example, use:

     try:
         import platform_specific_module 
     except ImportError:
         platform_specific_module = None 
    

    A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

    A good rule of thumb is to limit use of bare 'except' clauses to two cases:

    If the exception handler will be printing out or logging the traceback; at least the user will be aware that an error has occurred. If the code needs to do some cleanup work, but then lets the exception propagate upwards with raise. try...finally can be a better way to handle this case.

    0 讨论(0)
  • 2020-11-22 15:54

    Try this:

    try:
        #code
    except ValueError:
        pass
    

    I got the answer from this link, if anyone else run into this issue Check it out

    0 讨论(0)
  • 2020-11-22 15:57

    You will also catch e.g. Control-C with that, so don't do it unless you "throw" it again. However, in that case you should rather use "finally".

    0 讨论(0)
  • 2020-11-22 16:02

    Here are the places where i use except without type

    1. quick and dirty prototyping

    That's the main use in my code for unchecked exceptions

    1. top level main() function, where i log every uncaught exception

    I always add this, so that production code does not spill stacktraces

    1. between application layers

    I have two ways to do it :

    • First way to do it : when a higher level layer calls a lower level function, it wrap the calls in typed excepts to handle the "top" lower level exceptions. But i add a generic except statement, to detect unhandled lower level exceptions in the lower level functions.

    I prefer it this way, i find it easier to detect which exceptions should have been caught appropriately : i "see" the problem better when a lower level exception is logged by a higher level

    • Second way to do it : each top level functions of lower level layers have their code wrapped in a generic except, to it catches all unhandled exception on that specific layer.

    Some coworkers prefer this way, as it keeps lower level exceptions in lower level functions, where they "belong".

    0 讨论(0)
  • 2020-11-22 16:04

    Always specify the exception type, there are many types you don't want to catch, like SyntaxError, KeyboardInterrupt, MemoryError etc.

    0 讨论(0)
  • 2020-11-22 16:11

    It's almost always better to specify an explicit exception type. If you use a naked except: clause, you might end up catching exceptions other than the ones you expect to catch - this can hide bugs or make it harder to debug programs when they aren't doing what you expect.

    For example, if you're inserting a row into a database, you might want to catch an exception that indicates that the row already exists, so you can do an update.

    try:
        insert(connection, data)
    except:
        update(connection, data)
    

    If you specify a bare except:, you would also catch a socket error indicating that the database server has fallen over. It's best to only catch exceptions that you know how to handle - it's often better for the program to fail at the point of the exception than to continue but behave in weird unexpected ways.

    One case where you might want to use a bare except: is at the top-level of a program you need to always be running, like a network server. But then, you need to be very careful to log the exceptions, otherwise it'll be impossible to work out what's going wrong. Basically, there should only be at most one place in a program that does this.

    A corollary to all of this is that your code should never do raise Exception('some message') because it forces client code to use except: (or except Exception: which is almost as bad). You should define an exception specific to the problem you want to signal (maybe inheriting from some built-in exception subclass like ValueError or TypeError). Or you should raise a specific built-in exception. This enables users of your code to be careful in catching just the exceptions they want to handle.

    0 讨论(0)
提交回复
热议问题