The Python except keyword is used in exception handling. If there is an error in the program the remaining part of code does not execute. To handle the errors and know the type of error we use except block. This block is executed only when an error raised in the try block.
If the except block used without try block in the code it will raise an SyntaxError. In a program to know type of error occurred we use exception in the except block. It is a case-sensitive keyword which creates except block.
SyntaxFollowing is a syntax of the Python except keyword −
try: statement1 except: statement2Example
Following is an basic example of the Python except keyword −
try : print("Welcome to the Tutorialspoint") except: print("Error")Output
Following is the output of the above code −
Welcome to the TutorialspointType of error in except block
When we use Exception in the except block we can know the type of error raised in the try block.
ExampleHere, we have given a critical statement in the try block, which raise an error. We found the type of error in the except block −
var1 = 1 var2 = 0 try : print(var1//var2) except Exception as e: print("Type of Error :",e)
Output
Following is the output of the above code −
Type of Error : integer division or modulo by zeroUsing 'except' with finally
The finally block is executed regardless if the try block raises error or not.
ExampleFollowing is an example of except block with finally −
var1 = 9 var2 = 'zero' try : print(var1//var2) except Exception as e: print("Error :",e) finally: print("This block is executed irrespective to the error")
Output
Following is the output of the above code −
Error : unsupported operand type(s) for //: 'int' and 'str' This block is executed irrespective to the error
python_keywords.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4