Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading