In Python 2, are all exceptions that can be raise
d required to inherit from Exception?
That is, is the following sufficient to catch any possible exception:
try:
code()
except Exception as e:
pass
or do I need something even more general like
try:
code()
except:
pass
We can use try catch block to protect the code. Catch block is used to catch all types of exception. The keyword “catch” is used to catch exceptions.
except: accepts all exceptions, whereas. except Exception as e: only accepts exceptions that you're meant to catch. Here's an example of one that you're not meant to catch: >>> try: ...
Try and Except Statement – Catching all ExceptionsTry and except statements are used to catch and handle exceptions in Python. Statements that can raise exceptions are kept inside the try clause and the statements that handle the exception are written inside except clause.
In contrast, the except Exception as e statement is a statement that defines an argument to the except statement. e in the latter statement is utilized to create an instance of the given Exception in the code and makes all of the attributes of the given Exception object accessible to the user.
With the first variant you'll catch "all built-in, non-system-exiting exceptions" (https://docs.python.org/2/library/exceptions.html), and should catch user defined exceptions ("all user-defined exceptions should also be derived from this class").
For example, the first variant will not catch user-pressed Control-C (KeyboardInterrupt), but the second will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With