Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `try... except Exception as e` catch every possible exception?

In Python 2, are all exceptions that can be raised 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
like image 603
jaynp Avatar asked Nov 27 '14 05:11

jaynp


People also ask

Does try catch catch all exceptions?

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.

What does except exception as e mean?

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

Does exception catch all exceptions in Python?

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.

How do I catch exceptions to E?

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.


1 Answers

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.

like image 58
Sergii Dymchenko Avatar answered Sep 25 '22 11:09

Sergii Dymchenko