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?
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?
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.
except:
also catches (among many other things) NameError
and AttributeError
, so if you misspell something in the try
block (e.g. your "insert" function is actually called insert_one
because someone didn't value consistency as much as they should), it always silently tries to update()
. –
Heckelphone main()
)? –
Personally except Exception:
will catch NameError
and AttributeError
too. What makes bare except:
so bad is that it catches stuff that has no business being caught, e.g. SystemExit
(raised when you call exit
or sys.exit
, and now you've prevented an intended exit) and KeyboardInterrupt
(again, if the user hit Ctrl-C
, you probably don't want to keep running just to spite them). Only the latter makes any real sense to catch, and it should be caught explicitly. At least except Exception:
lets those two propagate normally. –
Tooth except:
...raise
to except Exception:
...raise
is really bad because you almost certainly did want to perform that cleanup or logging even if the user hit ctrl-c. –
Undecagon 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.
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.
Always specify the exception type, there are many types you don't want to catch, like SyntaxError
, KeyboardInterrupt
, MemoryError
etc.
except Exception:
avoid the above types that we don't want to catch? –
Urson except Exception
is fine. –
Uvula except Exception
catches SyntaxError
and MemoryError
because it is their base class. KeyboardInterrupt
, SystemExit
(raised by sys.exit()
) are not caught (they are immediate BaseException subclasses) –
Muriah 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".
Here are the places where i use except without type
That's the main use in my code for unchecked exceptions
I always add this, so that production code does not spill stacktraces
I have two ways to do it :
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
Some coworkers prefer this way, as it keeps lower level exceptions in lower level functions, where they "belong".
Try this:
try:
#code
except ValueError:
pass
I got the answer from this link, if anyone else run into this issue Check it out
© 2022 - 2024 — McMap. All rights reserved.