Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

Should I be ignoring this advice? Or is it Pythonic to always specific the exception type?

like image 547
HorseloverFat Avatar asked Feb 10 '13 11:02

HorseloverFat


People also ask

Why would using except exception be unhelpful?

Another disadvantage of passing and catching Exception (or bare except ) is that we will never know the second error when there are two errors in the code. The first error will always be caught first and we will get out of the try block.

Do not use bare except?

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:).

How do I fix broad except catching too exception exception?

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...

How can the try except statements handle errors in Python?

The Python try… except statement runs the code under the “try” statement. If this code does not execute successfully, the program will stop at the line that caused the error and the “except” code will run. The try block allows you to test a block of code for errors.


2 Answers

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.

like image 134
babbageclunk Avatar answered Sep 28 '22 12:09

babbageclunk


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.

like image 37
asheeshr Avatar answered Sep 28 '22 12:09

asheeshr