2

I have been trying to understand in general how the "as" keyword in python works so far and have learnt 3 cases for it

Case 1: import foo as bar

Case 2: with foo() as bar:

Case 3: except Exception as e:

I understand how the first 2 cases work, case 1 works assigning a package name to a different name, case 2 works using __entry__ and __exit__ methods within a class (say for ensuring resources close), where __entry__ returns the class bar is being assigned to.

However, case 3 seems different, I was looking through the docs which didn't seem to help and couldn't find much of an explanation anywhere. In this case Exception.args works differently to e.args and I have been trying to work out how this works behind the scenes, i.e. whatever methods may be called, or why it behaves differently

3
  • 2
    Exception is the exception class, and e is the exception object. Commented Feb 13, 2019 at 9:24
  • That as e basically assigns the name e to the instance of the exception that has been caught, so that you can refer to it (e.g. for logging) within the except block. Commented Feb 13, 2019 at 9:27
  • See docs.python.org/3/reference/… Commented Feb 13, 2019 at 9:28

4 Answers 4

2

In the except statement to associate a name to the exception being passed, as keyword is used.

Using as is the only way to assign the exception to a local in Python 3.x. But it is not required.

In Python 2.6+, we had 2 options , and as. since , is ambiguous in case of multicatch, which allows you to catch multiple exceptions in one except block. as is the preferred option.

In Python 2.5 and earlier, we use the ,for association, since as isn't supported.

Sign up to request clarification or add additional context in comments.

Comments

2

The phrase except A as b: states that in the above try clause all exceptions of class A (or a subclass thereof) are to be caught. The actually caught exception will be visible in the variable b then.

try:
  raise KeyError('example')
except LookupError as problem:
  print("I caught %r as problem." % problem)

This will print

I caught KeyError('example',) as problem.

2 Comments

Ahh I see, this makes a bit more sense, so the b in this case just catches an object of that class, and you can't go printing LookupError on its own un-initialized in this case if I understand correctly
@NightShade Yes. LookupError in my example is a class object while problem is an instance object. The first is the type, the second a value of this type. (Kind of.)
0

Try running this, which should make it clear.

try:
    zero = 0
    b = 1.0 / zero
except ArithmeticError as e:
    print( "Runtime error: ", e)

ArithmeticError is a Python exception class to be caught. e is an instance of that class, in this case the subclass ZeroDivisionError.

Comments

0

Calling e.args means that you can access the attributes of the exception object. But it won't catch BaseException SystemExit KeyboardInterrupt and GeneratorExit

try:
    i = 1/0
    print(i)
except Exception as e:
    print (e.args)

This will print:

('division by zero')

More ever If we rasie BaseException error

try:
    raise BaseException()
except Exception as e:
    print (e.args)

The output will be like this

runfile('W:/Summerizer/except.py', wdir='W:/Summerizer')
Traceback (most recent call last):

  File "<ipython-input-3-11e8f07e28c7>", line 1, in <module>
    runfile('W:/Summerizer/except.py', wdir='W:/Summerizer')

  File "C:\Users\adodhiwala\AppData\Local\conda\conda\envs\py35\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile
    execfile(filename, namespace)

  File "C:\Users\adodhiwala\AppData\Local\conda\conda\envs\py35\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "W:/Summerizer/except.py", line 10, in <module>
    raise BaseException()

BaseException

Here as is used to access more functions(args,message etc) so you can understand error more efficiently.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.