Module (29%)
Section (29%)

Advanced exceptions - named attributes

Now it’s time to dive more deeply into the interesting features of exception concepts and get familiar with the possible ways of using those concepts in your applications.

Once again, let's look at a typical try ... except statement.

try: print(int('a')) except ValueError as e_variable: print(e_variable.args)

The except clause may specify a variable after the exception name. In this example it’s an e_variable. This variable is bound to an exception instance with the arguments stored in the args attribute of the e_variable object.

Some exception objects carry additional information about the exception itself.

The ImportError exception – raised when the import statement has trouble trying to load a module. The attributes are:

  • name – represents the name of the module that was attempted to be imported;
  • path – represents the path to any file which triggered the exception, respectively. Could be None.

See the output of this snippet to analyze the attributes' values.


Code

try:
import abcdefghijk

except ImportError as e:
print(e.args)
print(e.name)
print(e.path)
{{ dockerServerErrorMsg }} ×
{{ errorMsg }} ×
{{ successMsg }} ×