Difference Between Except: and Except Exception as E:

Difference between except: and except Exception as e:

In the second you can access the attributes of the exception object:

>>> def catch():
... try:
... asd()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
global name 'asd' is not defined ("global name 'asd' is not defined",)

But it doesn't catch BaseException or the system-exiting exceptions SystemExit, KeyboardInterrupt and GeneratorExit:

>>> def catch():
... try:
... raise BaseException()
... except Exception as e:
... print e.message, e.args
...
>>> catch()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in catch
BaseException

Which a bare except does:

>>> def catch():
... try:
... raise BaseException()
... except:
... pass
...
>>> catch()
>>>

See the Built-in Exceptions section of the docs and the Errors and Exceptions section of the tutorial for more info.

What does ''except Exception as e'' mean in python?

except Exception as e, or except Exception, e (Python 2.x only) means that it catches exceptions of type Exception, and in the except: block, the exception that was raised (the actual object, not the exception class) is bound to the variable e.

As for finally, it's a block that always gets executed, regardless of what happens, after the except block (if an exception is raised) but always before anything else that would jump out of the scope is triggered (e.g. return, continue or raise).

In Python, what's the difference between 'except Exception as e' and 'except Exception, e'

This PEP introduces changes intended to help eliminate ambiguities in Python's grammar, simplify exception classes, simplify garbage collection for exceptions and reduce the size of the language in Python 3.0.

PEP 3110: "Catching Exceptions in Python 3000"

What is the difference between except and except BaseException

Practically speaking, there is no difference between except: and except BaseException:, for any current Python release.

That's because you can't just raise any type of object as an exception. The raise statement explicitly disallows raising anything else:

[...] raise evaluates the first expression as the exception object. It must be either a subclass or an instance of BaseException.

Bold emphasis mine. This has not always been the case however, in older Python releases (2.4 and before) you could use strings as exceptions too.

The advantage then is that you get to have easy access to the caught exception. In order to be able to add as targetname, you must catch a specific class of exceptions, and only BaseException is going to do that.

You can still access the currently active exception by using sys.exc_info() though:

except:
be = sys.exc_info()[1]

Pick what you feel is more readable for your future self and for your colleagues.

Why is except: able to catch this error but not except Exception, e:?

This exception does not derive from Exception. It looks like a SystemExit, which derives from BaseException directly. except Exception only catches instances of Exception.

If you really want to catch absolutely all exceptions, you can do that with

except BaseException as e:

SystemExit is thrown by sys.exit and a few similar functions to cause an interpreter shutdown (or at least end the thread) while still running __exit__ methods and finally blocks. It can also be thrown manually.

BaseException exists so SystemExit and a few similar exceptions aren't caught by except Exception blocks that usually aren't intended to handle them. It's similar to Java's Throwable. Personally, I wish plain except: blocks didn't catch BaseException; it defeats some of the purpose of having BaseException in the first place.

Use of except Exception vs. except ... raise in Python

No, your code is not equivalent, for several reasons:

  • A blank except: catches all exceptions, including those derived from BaseException (SystemExit, KeyboardInterrupt and GeneratorExit); catching Exception filters out those exceptions you generally want to avoid catching without a re-raise. In older Python releases, it would also catch string exceptions (no longer permitted).
  • The except Exception as e catches subclasses, but then raises a new Exception() instance; the specific type information can't be used anymore in downstream try...except statements.
  • In Python 3, raising a new exception from an exception handler creates an exception chain (where the original exception is added as the Exception.__context__ attribute, see Python "raise from" usage)
  • The message is updated; that's probably the whole point here, is to give the exception a different message.

The code you found is.. rather bad practice. The top-level exception handler should just catch and print a message and perhaps a traceback, rather than re-raise the exception with a new message (and in Python 2 lose all information on the original exception, in Python 3 make it inaccessible to exception matching in later handlers).

generic except clause works Exception as ex does not catch exception in python

SystemExit inherits from BaseException not from Exception so to catch it you need except BaseException as e:. This is deliberate to prevent accidental capture of the exception via except Exception as e:

Functional difference in exception handling between consecutive except, nested try, tuple exception with if else code blocks

I think either of the first two options are fine.

Personally I find I think the first is easier to read for a short simple function although if my_func was larger and more complex with nesting then I would opt for the second option as it makes it clear where exactly where sycopg2.Error may be raised.

The wouldn't use the third option. If you want to catch multiple exceptions use this syntax:

except (RuntimeError, TypeError, NameError):
pass


Related Topics



Leave a reply



Submit