How can I write a try/except block that catches all exceptions?
10 Answers
Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:
import traceback import logging try: whatever() except Exception as e: logging.error(traceback.format_exc()) # Logs the error appropriately. You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.
The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.
15 Comments
Exception. Note that it's impossible to raise an int as an exception, and attempting to do so raises a TypeError exception, which is what would be caught by the enclosing except Exception clause in such a case. On the other hand, an old-style class can be raised and qualifies as a "non-exception" that doesn't subclass Exception - this will be caught by a bare except clause but not by an except Exception clause.TypeErrorsys.exit() usually means you expect the app to terminate but if you catch SystemExit it won't. Likewise if you hit control-C on a running script (Ctrl-break on windows) you expect the program to stop, not to catch the error and keep going. But you can catch either/both of these if you want to do cleanup before existing.except BaseException as e: notify_user(e); raise that would catch all exceptions and do whatever notification you need, but I don't know HPC so you might want to ask as a new SO question.You can but you probably shouldn't:
try: do_something() except: print("Caught it!") However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:
try: f = open('myfile.txt') s = f.readline() i = int(s.strip()) except IOError as (errno, strerror): print("I/O error({0}): {1}".format(errno, strerror)) except ValueError: print("Could not convert data to an integer.") except: print("Unexpected error:", sys.exc_info()[0]) raise 14 Comments
except Exception:.To catch all possible exceptions, catch BaseException. It's on top of the Exception class hierarchy:
Python 3: https://docs.python.org/3.12/library/exceptions.html#exception-hierarchy
Python 2.7: https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy
try: something() except BaseException as error: print('An exception occurred: {}'.format(error)) But as other people mentioned, you would usually not need this, only for very specific cases.
6 Comments
In Python, all exceptions must be instances of a class that derives from BaseException, but if you can omit it for a general case - omit it, problem is, linters wine about it.SIGINT that raises KeyboardInterrupt in the first place. Sure, you can catch KeyboardInterrupt, but it's just one of many signals that could terminated your program prematurely. Those don't generate any kind of exception, so you may as well handle them all uniformly.BaseException like this is rarely what you want. Do you seriously want to catch keyboard interupts and sys.exit? Probably NOT! All user-defined exceptions should inherit from Exception. take a look at the exception class heirarchy. dotnettutorials.net/wp-content/uploads/2020/07/…You can do this to handle general exceptions
try: a = 2/0 except Exception as e: print e.__doc__ print e.message 8 Comments
message attribute.Very simple example, similar to the one found here:
http://docs.python.org/tutorial/errors.html#defining-clean-up-actions
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.
try: print "Performing an action which may throw an exception." except Exception, error: print "An exception was thrown!" print str(error) else: print "Everything looks great!" finally: print "Finally is called directly after executing the try statement whether an exception is thrown or not." In the above example, you'd see output in this order:
1) Performing an action which may throw an exception.
2) Finally is called directly after executing the try statement whether an exception is thrown or not.
3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.
Hope this helps!
3 Comments
except: catch that? But it doesn't give me a handle for e though :(except Exception as error: -- If you're running Python3.There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method(): try: sqrt = 0**-1 except Exception as e: print(e) bad_method() Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
- Line number for your code
- File name
- The actual error in more verbose way
The only drawback is tracback needs to be imported.
import traceback def bad_method(): try: sqrt = 0**-1 except Exception: print(traceback.print_exc()) bad_method() 3 Comments
except: catch that? But it doesn't give me a handle for e though :(traceback.print_exc()?0**-1 is not a square root, it raises ZeroDivisionError: 0.0 cannot be raised to a negative power. If you really want to calculate a square root, you must use import math; math.sqrt(-1) which will raise ValueError: math domain error.I've just found out this little trick for testing if exception names in Python 2.7 . Sometimes i have handled specific exceptions in the code, so i needed a test to see if that name is within a list of handled exceptions.
try: raise IndexError #as test error except Exception as e: excepName = type(e).__name__ # returns the name of the exception 2 Comments
except: catch that? But it doesn't give me a handle for e though :(I am adding the bonus method that can catch the exception with full traceback which can help you to understand the error more.
Python 3
import traceback try: # your code goes here except Exception as e: print(e) traceback.print_exc() 1 Comment
try: whatever() except: # this will catch any exception or error It is worth mentioning this is not proper Python coding. This will catch also many errors you might not want to catch.
1 Comment
First of all, there are exceptions that you want them to break your code (as when this error happens your code will not function anyways!) and exceptions you want to capture silently/smoothly. Try differentiating them. You may not want to capture all exceptions there are!
Second, instead of capturing everything, you could take the time and go through the logs of your process. Let's say you are getting a different/third-party exception, for example from a cloud service provider like GCP. In the logs, you could find the exception you are getting. Then, you could do something like this:
from google.api_core.exceptions import ServiceUnavailable, RetryError for i in range(10): try: print("do something") except ValueError: print("I know this might happen for now at times! skipping this and continuing with my loop" except ServiceUnavailable: print("our connection to a service (e.g. logging) of gcp has failed") print("initializing the cloud logger again and try continuing ...") except RetryError: print("gcp connection retry failed. breaking the loop. try again later!) break For the rest (errors that might or might not happen), I am leaving room for my code to crash if I get an unexpected exception! This way I could understand what is going on and improve my code by capturing edge cases.
If you want this to never crash for some reason, for example if it is a code embedded in a remote hardware that you cannot easily access, you can add a generic exception catcher at the end:
except Exception as e: print(f"something went wrong! - {e}") You can also take a look at Python 3 exception hierarchy here. The difference between Exception and BaseException is that, Exception will not catch SystemExit, KeyboardInterrupt, or GeneratorExit
sys.stderrand possibly logged. That is a perfectly valid and common exception.try: whatever() except Exception as e: exp_capture()?except: passa bad programming practice?