Reputation: 456
I am learning 'Exceptions' in Python.
Consider the following code :
def fancy_divide():
try:
print(5/0)
except Exception:
print(Exception)
If I run the above code, ie
fancy_divide()
it prints out <class 'Exception'>
.
But if I modify the code :
def fancy_divide():
try:
print(5/0)
except Exception as ex:
print(ex)
It prints out 'division by zero' on calling the function fancy_divide()
.
Why this difference?
I thought that the 'as' keyword is just to rename objects.
Upvotes: 4
Views: 145
Reputation:
On the last line of your first fancy_divide
function, you printed the Exeption
class itself, not an instance of the Exception
class. On the third line of your updated code, where you used the as
keyword, you were trying to catch an instance of the Exception
class or its subclasses and assign it to the variable ex
if you got an error. Note: an instance is different from the actual class (well, I hope you already know this)
You can see this when you compare the contents of ex
to Exception
:
def fancy_divide_return():
try:
print(5/0)
except Exception as ex:
return Exception, ex
>>> the_class, the_instance = fancy_divide_return()
>>> the_class
<class 'Exception'>
>>> the_instance
ZeroDivisionError('division by zero',)
>>> type(the_class)
<class 'type'>
>>> type(the_instance)
<class 'ZeroDivisionError'>
Upvotes: 1
Reputation: 6030
It says that for scope following as
there will be a variable called ex
that was created from Exception
.
In your case the difference is that in example one you are printing out the class Exception, in example two you are printing an object of type Exception.
>>> print(int)
<class 'int'>
>>> print(int(1))
1
>>>
I often see and use it when opening a file:
with open(filename) as f:
f.read()
In python documentation it has the following example:
>>> try:
... raise NameError('HiThere')
... except NameError:
... print('An exception flew by!')
... raise
...
An exception flew by!
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: HiThere
Notice that the Code doesn't do anything with the class NameError
. Because they are in that block they know that it's a NameError
. If they wanted to do something with the error object that was thrown then they would have to rewrite the code with as
:
>>> try:
... raise NameError('HiThere')
... except NameError as e:
... print(e)
... print('An exception flew by!')
... raise
...
Upvotes: 1