python catch several exceptions - python

I have some code that is calling several methods from multiple functions. Some of these methods may raise an exception. Each can raise a different type of exception. In my main script, I would like to log the exception and then just exit. So, no matter what the exception type, log it and exit
My question is this: is it better to list all the exceptions that might be generated, or just catch a generic Exception? Which is more pythonic?
example:
try:
some_stuff()
except (Exc1, Exc2, Exc3) as exc:
loger.exception(exc)
or this:
try:
some_stuff()
except Exception as exc:
loger.exception(exc)

Your plan to catch exception in main code, log it and terminate is good one.
There could be exceptions, which are fine and do not mean, you shall consider them as problem, e.g. KeyboardInterrupt
The strategy could be:
first, catch all the exceptions, which you expect to be fine and pass
then catch general Exception, log it and terminate.
The code could look like:
try:
some(stuff) # ...
# First, resolve expected exceptions
except KeyboardInterrupt:
pass
# Finally, log unexpected ones
except Exception as exc:
logger.exception(exc)
return # time to terminate
When is catching exceptions explicitly a failure
The advice to be better by explicitly catching all expected exceptions comes short in case an unexpected exception happens. Your plan to catch whatever comes to log file sounds good and provide enough information for resolving the problems later on.
Imagine, you have a daemon, which shall run and run. Under some conditions, it might fail.
With only expecting explicit exception, it may happen, unexpected exception happens, no expect
would have a chance to log this to a log file, stacktrace would be printed to stdout and forgotten
and program terminates.
This is clear and very reasonable use case for catching exception generally.

From the documentation:
Because except: catches all exceptions, including SystemExit,
KeyboardInterrupt, and GeneratorExit (which is not an error and should
not normally be caught by user code), using a bare except: is almost
never a good idea. In situations where you need to catch all “normal”
errors, such as in a framework that runs callbacks, you can catch the
base class for all normal exceptions, Exception. Unfortunately in Python 2.x it is
possible for third-party code to raise exceptions that do not inherit from Exception, so
in Python 2.x there are some cases where you may have to use a bare except: and manually > re-raise the exceptions you don’t want to catch.
In general, it is better to catch explicit exceptions. In Python 2, how you are doing it can result in exceptions you still don't catch if an external module is throwing something that doesn't inherit exception.
By catching explicit exceptions you are able to handle errors you know can occur. If you catch all, your application could do something unexpected and you may handle it incorrectly.
Additionally, do you really want to catch someone using Ctrl+C to end your program?

In all languages, times, and places it is better to specify specific exceptions. That way you won't mask a condition you didn't expect to. NEVER catch Exception in production code unless you have a very, very good reason, or your handler is truly generic. An example of a suitably generic handler is one which logs, performs cleanup, and reraises.

Take a note out of Tim Peter's book:
>>> import this
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
...
Explicit is better than implicit. It's more "pythonic" to write out the possible exceptions.

Related

Is it bad to "catch" exceptions if all you do is print it to error?

Just a quick little question about coding in general.
Say you're using a try-catch block, but all you do with the exception is print it to stderr. In this case, are you better off simply letting the error happen and letting it print on its own? Or is it still better to catch the exception so that it is documented for other coders?
In languages like Java, there is a "throws exception", but as far as I can tell Python has nothing of that kind.
Thanks
If we don't catch exception, then the normal flow of control will break where the exception occurred and will jump to the point where the exception is caught or the program will just terminate after printing the exception.
Not catching exception might be ok for simple programs, but for complex applications where we have multiple methods and libraries, we would wish to catch the exception where in the part of the program where it occurs and handle it according to our need. In web applications we may handle the exception and display user understandable error message.
In general, its always better to handle the exception even if we just print it to the logs.
I would always handle and catch the exception. No matter, whether small or large project. Because by catching an exception, you can give the user precise information WHAT he e.g. entered incorrectly (too small / too large a number ...) So the entire program code does not always have to be run through, but it left at the point where the exception is thrown.
In python you can throw like in java (throw exception) but with raise exception.
Here a small, understanding introduce for python exception. So I learned the exception in python. Good luck!

Exceptions vs Errors in Python

I come from Java where Exceptions and Errors are quite different things and they both derive from something called Throwable.
In Java normally you should never try to catch an Error.
In Python though it seems the distinction is blurred.
So far after reading some docs and checking the hierarchy I have the following questions:
There are syntax errors which of course cause your program not to be able to start at all. Right?
"Errors detected during execution are called exceptions and are not unconditionally fatal" (per the tutorial). What does "fatal" mean here? Also, some objects like AttributeError are (by the above definition) actually exceptions even though they contain Error in their names, is that conclusion correct?
Some classes derive from Exception but contain Error in their name. Isn't this confusing? But even so it means that Error in the name is in no way special, it's still an Exception. Or not... ?
"All built-in, non-system-exiting exceptions are derived from [Exception]" (quote from here)
So which ones are system-exiting exceptions and which ones are not? It is not immediately clear. All user-defined exceptions should also be derived from Exception. So basically as a beginner do I need to worry about anything else but Exception? Seems like not.
Warnings also derive from Exception. So are warnings fatal or system-exiting or none of these?
Where does the AssertionError fit into all of this? Is it fatal or system exiting?
How does one know or specify that some Exception class represents fatal or system-exiting exception?
Yes. SyntaxError isn't catchable except in cases of dynamically executed code (via eval/exec), because it occurs before the code is actually running.
"Fatal" means "program dies regardless of what the code says"; that doesn't happen with exceptions in Python, they're all catchable. os._exit can forcibly kill the process, but it does so by bypassing the exception mechanism.
There is no difference between exceptions and errors, so the nomenclature doesn't matter.
System-exiting exceptions derive from BaseException, but not Exception. But they can be caught just like any other exception
Warnings behave differently based on the warnings filter, and deriving from Exception means they're not in the "system-exiting" category
AssertionError is just another Exception child class, so it's not "system exiting". It's just tied to the assert statement, which has special semantics.
Things deriving from BaseException but not Exception (e.g. SystemExit, KeyboardInterrupt) are "not reasonable to catch" (or if you do catch them, it should almost always be to log/perform cleanup and rethrow them), everything else (derived from Exception as well) is "conditionally reasonable to catch". There is no other distinction.
To be clear, "system-exiting" is just a way of saying "things which except Exception: won't catch"; if no except blocks are involved, all exceptions (aside from warnings, which as noted, behave differently based on the warnings filter) are "system-exiting".
Exceptions are designed for the programmer to know how to handle them such as outOfRange
Once an exception arises the programmer has to decide how to handle it and the code can continue to operate relatively smoothly
On the other hand an error indicates a problem that the programmer could not foresee as an import error or a memory error
Errors can still be addressed and ensure that the software continues to run but apparently not everything will be able to continue to work smoothly.

Python determine whether an exception was thrown (regardless of whether it is caught or not)

I am writing tests for some legacy code that is littered with catch-all constructs like
try:
do_something()
do_something_else()
for x in some_huge_list():
do_more_things()
except Exception:
pass
and I want to tell whether an exception was thrown inside the try block.
I want to avoid introducing changes into the codebase just to support a few tests and I don't want to make the except cases more specific for fear of unintentionally introducing regressions.
Is there a way of extracting information about exceptions that were raised and subsequently handled from the runtime? Or some function with a similar API to eval/exec/apply/call that either records information on every raised exception, lets the user supply an exception handler that gets run first, or lets the user register a callback that gets run on events like an exception being raised or caught.
If there isn't a way to detect whether an exception was thrown without getting under the (C)Python runtime in a really nasty way, what are some good strategies for testing code with catch-all exceptions inside the units you're testing?
Your only realistic option is to instrument the except handlers.
Python does record exception information, which is retrievable with sys.exc_info(), but this information is cleared when a function exits (Python 2) or the try statement is done (Python 3).
A good strategy would be testing observable behaviour. Since exceptions were explicitly excluded from the observable behaviour I do not think you should be testing whether an exception was raised or not.

Python - Why is an exception type needed to be put after an 'except'? [duplicate]

This question already has answers here:
Should I always specify an exception type in `except` statements?
(7 answers)
How to properly ignore exceptions
(12 answers)
Closed 8 years ago.
When you use try/except in python, why do you need an exception type to be named after except? Wouldn't it be easier to just catch all exceptions?
try:
#dosomething
except Exception:
#dosomething
Why is the 'Exception' needed after except?
Because you might handle different exceptions different ways.
For example, if you're attempting a network operation, and the network address you're trying to reach can't be resolved, that's likely due to user error, and you'll want to get the user involved, while some other kinds of errors can simply be retried after a short wait.
It's a good practice in exception handling to handle only the narrowest set of exceptions you expect at any one point in the code, and to only catch those exceptions that you're sure you know how to handle. A catch-all exception handler violates this principle.
From a purely syntactic point of view, this is acceptable code:
try:
# Do something
except:
print "Something went wrong."
HOWEVER, it's not a very good idea to do this a lot of the time. By catching all exceptions and not even saving the name, you're losing all information about where the error was. Just seeing Something went wrong. printed out is both useless and frustrating. So even if you don't want to handle each exception individually, you'd want to save the exception information at the very least.
try:
# Do something.
except Exception, e:
print "Encountered error " + str(e) + " during execution. Exiting gracefully."
The above code is something you might do if you absolutely can't let your program exit abruptly, for example.
EDIT: changed the answer to clarify that it's a bad idea, though possible.
Why and how to catch exceptions
Exceptions are really helpful, but they shall be handled in different manner depending on what code
you write.
Core distinction is, if your code is top level one (last resort to handle exceptions) or inner one.
Another aspect is, if some exceptions are excepted or unexpected.
Expected exceptions (like file, you are trying to use is missing) shall be handled, if the code has
a chance to do anything about it.
Unexpected exceptions shall not be handled unless you have to do so in top level code.
Handling exceptions in top level code
If it does not matter, that your code throws a bit ugly stack trace under some circumstances, simply
ingore the unexpected exceptions. This is mostly very efficient, as the code is kept simple, and
stack trace give you good chance to find out, what went wrong.
If you have to make your script "well behaving" - you could catch the exception and print some nice
looking excuse for what went wrong.
Handling exceptions in lower level code (modules, functions)
In your lower level code, you shall catch all expected exceptions, and the rest shall be ignored and
thrown up to higher levels, where is better chance to handle it properly.
If you have no expected exception, simply do not use try .. except block.
Printing some excuses from lower level code is mostly inappropriate (higher level code has no chance
t silence your printouts.
To your question - why except Exception
except with explicitly mentioned type of exception is the only solution to use for expected types
of exceptions. Without mentioning the type (or types), you are catching all and this is bad habit
unless you are in top level code.
As usual, there are exceptions to the recommendations above, but they are occurring less often than one
usually expects.
Different exceptions require different fixing. For example, when I was writing a python irc bot, i would have one exception for invalid access to a string, and that code in the except would try to remedy it. I also had one for bad sockets that would try to deduce why it went bad and fix it. I can't have these under one exception because they are fixed differently

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?
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.
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.
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
quick and dirty prototyping
That's the main use in my code for unchecked exceptions
top level main() function, where i log every uncaught exception
I always add this, so that production code does not spill stacktraces
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".
Try this:
try:
#code
except ValueError:
pass
I got the answer from this link, if anyone else run into this issue Check it out

Categories

Resources