What exactly happens when you create an alias of the Exception class?

Advertisements
try:
    0/0
except Exception as e:
    print(e)

The above code prints division by zero as one would expect. But if we try to print without creating the alias:

try:
    0/0
except Exception:
    print(Exception)

It simply prints <class 'Exception'>. What is happening here? The as keyword is used to create an "alias". If the error message "division by zero" is an attribute of the Exception class, then why does creating an alias make it equal to said attribute?

Is it possible to print the error message without creating the alias?

>Solution :

The documentation of Python states this:

The except clause may specify a variable after the exception name. The variable is bound to the exception instance which typically has an args attribute that stores the arguments. For convenience, builtin exception types define str() to print all the arguments without explicitly accessing .args.

It means that the variable that is passed after the name of Exception has additional attributes to display the specific exception occured.

Leave a ReplyCancel reply