7

The typical structure for exception handling is below:

try:
    pass
except Exception, e:
    raise
else:
    pass
finally:
    pass

May I know what does except Exception, e:orexcept Exception as e: mean? Typically I will use print (e) to print the error message but I am wondering what the program has done to generate the e.

If I were to construct it in another way (below), how would it be like?

except Exception:
    e = Exception.something

What should the method be to replace the something?

When the body of code under try gives no exception, the program will execute the code under else. But, what does finally do here?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
lxjhk
  • 567
  • 2
  • 7
  • 13
  • 3
    There sure are a lot of questions in the question. I would recommend you read the documentation for `try`: https://docs.python.org/3/reference/compound_stmts.html#the-try-statement That will answer most of them. –  Dec 17 '14 at 02:41
  • Possible duplicate of [Difference between except: and except Exception as e: in Python](https://stackoverflow.com/questions/18982610/difference-between-except-and-except-exception-as-e-in-python) – Stevoisiak May 22 '18 at 18:05
  • Unless you are *specifically* asking about how to solve a cross-version compatibility problem (in which case your question should obviously describe that problem) you should not mix the [tag:python-2.7] and [tag:python-3.x] tags. – tripleee Aug 20 '19 at 14:14

1 Answers1

18

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

Max Noel
  • 8,810
  • 1
  • 27
  • 35
  • Is "except Exception, e:" same as "except Exception as e:"? And does the 1st example catch base exceptions? – variable Jul 23 '19 at 07:26
  • Both forms do the exact same thing. Neither catches base exceptions (e.g. `SystemExit` or `KeyboardInterrupt`, which inherit from `BaseException` but not from `Exception`). If you're raising things that *don't* inherit from `BaseException` (in Python 2 you can raise arbitrary objects, e.g. strings, but you shouldn't), they won't be caught either. – Max Noel Jul 25 '19 at 21:05