A try and except block is used for error handling in Python.
Try
: Helps to test the code. If the code inside the try block is error free it is executed. Otherwise the error gets caught and control goes to the except block.Except
: Except displays the error message.Else
: Executes if there is no error in the code in the try block.Finally
: Executes independently of the try-except block results.The Else
and Finally
block are optional but it is considered a good programming practice to include them.
There are two types of error that can occur:
The following are the list of exception error that arises:
The general syntax is:
try:
statement1 #test code
except:
statement2 #error message
finally:
statement3 #must execute
The following code explains how error gets caught in the try block and gets printed in the except block:
try:print(variable)except:print("Variable is not defined")
If multiple errors may arise after the execution of one try block, we may use multiple except blocks to handle them.
Note: It is compulsory that the keyword
NameError
is written in front of the first except statement.
try:print(variable)except NameError:print("Variable is not defined")except:print("Seeems like something else went wrong")
The following code explains how else block gets executed when the try executed correctly:
try:variable="Python Programming";print(variable)except:print("An exception occurred")else:print("Else executes: Try block executed correctly")
The following code explains how error gets caught in the try block and gets printed in the except block and then the finally block gets executed:
try:print(variable)except:print("An exception occurred")finally:print("Always execute this block")