Python exception handling
In programming, an exception is an event, during the program’s normal execution it can occur and disrupts the program instructions. The way of handling those types of events and keeping the program’s normal execution is called exception handling. This Python tutorial section will teach you the way of exception handling.
Objectives
-
Python try and catch exceptions
-
Python raising exceptions
Python try and catch exceptions
Exception handler has basically 3 parts, those are
-
try: The try block lets us test a block of code for errors.
-
except: The except block lets us handle the error.
-
finally: The finally block lets us execute code, regardless of the result of the try- and except blocks.
there is another part call else
-
else : The else block lets us execute code when there is no error.
Syntax
try:
'Actual code to be execute'
except:
'Something went wrong during execution'
else:
'There is nothing wrong in code (Only execute when there is no exception)'
finally:
'Called every time when the execution done dosen't matter failed or success'
Code
try:
print("Main Block")
except:
print("Something went wrong")
else:
print("Something else")
finally:
print("The 'try except' is finished")
Output
Main Block
Something else
The 'try except' is finished
Process finished with exit code 0
Python raising exceptions
Raising an exception is a technique for interrupting the normal flow of execution in a program. The raise statement allows the programmer to force a specified exception to occur.
Code
role = "user"
if role != "admin":
raise Exception("Restricted area")
Output
Traceback (most recent call last):
File "...\src\exception_handling.py", line 16, in <module>
raise Exception("Restricted area")
Exception: Restricted area
Process finished with exit code 1