Noogrammer
Noogrammer

Reputation: 37

How the 'as' keyword works in exception handling?

In the code below

>>> try:
...     a = 12 / 0
... except Exception as e:
...     print(e)
... 
division by zero
>>> 

Google says 'the as keyword is used to create an alias.'

Then why this below code does not work?

>>> try:
...     a = 12 / 0
... except Exception:
...     print(Exception)
... 
<class 'Exception'>
>>> 

According to some sources it creates an object of the Exception class.

Then why the following code print nothing?

>>> try:
...     a = 12 / 0
... except Exception:
...     a = Exception()
...     print(a)
... 

>>> 

My questions are:

  1. If the as keyword acts as an alias, why the second example did not work (instead of printing error it printed reference to Exception class)?

  2. If the as keyword creates an object of the Exception class, why the third example did not work (instead of printing the error it did not print anything)?

Upvotes: 1

Views: 215

Answers (1)

Tim Roberts
Tim Roberts

Reputation: 54767

You are misreading the reference. The as keyword is used to create an alias, but only in the import statement. Its meaning with except is entirely different. In that case, it merely declares a variable that will hold the exception object. If you say except Exception as e, then e will be an object of type Exception.

In your final example:

try:
    a = 12/0
except Exception:
    a = Exception()
    print(a)

You are not capturing the exception that was thrown. Instead, you are creating a brand new Exception option. Such an object does not yet hold an exception, so nothing prints. If you want the exception that was caught, you must use the as clause.

Upvotes: 4

Related Questions