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

Question:

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?

Asked By: HorseloverFat

||

Answers:

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

Answered By: Ulrich Eckhardt

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

Answered By: Pavel Anossov

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.

Answered By: asheeshr

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.

Answered By: babbageclunk

Not specfic to Python this.

The whole point of exceptions is to deal with the problem as close to where it was caused as possible.

So you keep the code that could in exceptional cirumstances could trigger the problem and the resolution “next” to each other.

The thing is you can’t know all the exceptions that could be thrown by a piece of code. All you can know is that if it’s a say a file not found exception, then you could trap it and to prompt the user to get one that does or cancel the function.

If you put try catch round that, then no matter what problem there was in your file routine (read only, permissions, UAC, not really a pdf, etc), every one will drop in to your file not found catch, and your user is screaming “but it is there, this code is crap”

Now there are a couple of situation where you might catch everything, but they should be chosen consciously.

They are catch, undo some local action (such as creating or locking a resource, (opening a file on disk to write for instance), then you throw the exception again, to be dealt with at a higher level)

The other you is you don’t care why it went wrong. Printing for instance. You might have a catch all round that, to say There is some problem with your printer, please sort it out, and not kill the application because of it. Ona similar vain if your code executed a series of separate tasks using some sort of schedule, you wouldnlt want the entire thing to die, because one of the tasks failed.

Note If you do the above, I can’t recommend some sort of exception logging, e.g. try catch log end, highly enough.

Answered By: Tony Hopkinson

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

Answered By: nipil

Try this:

try:
    #code
except ValueError:
    pass

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

Answered By: Mekanic
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.