Python 3 Part 9 - Exception Handing
Table of content
- Exceptions
- Handling exceptions
- Finally block
- How to raise exceptions
Exceptions
Even if the code is logically correct but sometimes It may cause an unwanted behavior while executing the code is termed as Exceptions.
Python has a list of built-in exception list, that can found here : https://docs.python.org/3/library/exceptions.html#bltin-exceptions
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
Handling Exception
Syntax for exception handling.
try:
statements
except <Exception_Name1>:
statements
except <Exception_Name2>:
statements
More generic way to handles any exception which occurs in try block.
try:
statements
except:
statements
Finally block
Finally block executed irrespective of exception occurred or not. Syntax for finally block.
try:
statements
except:
statements
finally:
statements
Example 1 :
try:
num = 1/0
except ZeroDivisionError:
print("Zero Division Error occurred")
finally:
print("In finally-block")
output
Zero Division Error occurred
In finally-block
Example 2 :
try:
num = 1/0
except :
print("Zero Division Error occurred")
finally:
print("In finally-block")
output
Zero Division Error occurred
In finally-block
We can handling multiple exceptions in a single except block :
except (RuntimeError, TypeError, NameError):
pass
How to raise Exceptions?
We can throw an exception using the raise keyword. Below example raises generic Exception and NameError.
>>> raise Exception("Exception Occurred")
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
raise Exception("Exception Occurred")
Exception: Exception Occurred
>>> raise NameError("Name Error Exception")
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
raise NameError("Name Error Exception")
NameError: Name Error Exception
>>>
Thank you folks. If you like this Python 3 post, please do checkout my other post on Django with Python 3 series