Note that there are some explanatory texts on larger screens.

plurals
  1. POCatching Python runtime errors only
    primarykey
    data
    text
    <p>I find myself handling exceptions without specifying an exception type when I call code that interacts with system libraries like shutil, http, etc, all of which can throw if the system is in an unexpected state (e.g. a file locked, network unavailable, etc)</p> <pre><code>try: # call something except: print("OK, so it went wrong.") </code></pre> <p>This bothers me because it also catches <code>SyntaxError</code> and other exceptions based in programmer error, and I've seen recommendations to avoid such open-ended exception handlers.</p> <p>Is there a convention that all runtime errors derive from some common exception base class that I can use here? Or anything that doesn't involve syntax errors, module import failures, etc.? Even <code>KeyError</code> I would consider a bug, because I tend to use dict.get() if I'm not 100% sure the key will be there.</p> <p>I'd hate to have to list every single conceivable exception type, especially since I'm calling a lot of supporting code I have no control over.</p> <p><strong>UPDATE:</strong> OK, the answers made me realize I'm asking the wrong question -- what I'm really wondering is if there's a Python convention or explicit recommendation for library writers to use specific base classes for their exceptions, so as to separate them from the more mundane <code>SyntaxError</code> &amp; friends. </p> <p>Because if there's a convention for library writers, I, as a library consumer, can make general assumptions about what might be thrown, even if specific cases may vary. Not sure if that makes more sense?</p> <p><strong>UPDATE AGAIN</strong>: Sven's answer finally led me to understand that instead of giving up and catching everything at the top level, I can handle and refine exceptions at the lower levels, so the top level only needs to worry about the specific exception type from the level below.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload