Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python try Keyword



The Python, try keyword is used in exception handling. A critical statements are accepted in the try block. For example, when we divide two numbers the code executes without an error but when we divide a number with zero it will raise an exception, this is a critical statement.

The try block is used to check code for errors i.e the code inside the block is executed when there is no error in the program. To handle the error raised in the try block we need except block. It is a case-sensitive keyword.

When we use the try block alone without except or finally we will get an SyntaxError

Syntax

Following is the syntax of the Python try keyword −

try:
  statement1
  statement2

Example

Following is an basic example of the Python try keyword −

try :
    print("Welcome to the Tutorialspoint")
except:
    print("Error")

Output

Following is the output of the above code −

Welcome to the Tutorialspoint

SyntaxError in try block

Without except block or finally block, the try block cannot be used it will raise an SyntaxError.

Example

Lets see what happens if the try block is used without except or finally in the code with the following example

print("Hello")
try:
    print("Welcome")

Output

Following is the output of the above code −

File "/home/cg/root/65861/main.py", line 4
    
SyntaxError: expected 'except' or 'finally' block

try block with finally

The finally block will be executed regardless, if the try block raises an error or not. Without except block the finally can be used along with try block, but if there is any error raised than the finally block cannot be executed.

Example

Here, in the try block there is executed along with finally because there is no error raised in the try block −

var1 = 4
var2 = 3
try:
    print(var1//var2)
except:
    print("Invalid")
finally:
    print("This block is executed irrespective to the error")  

Output

Following is the output of the above code −

1
This block is executed irrespective to the error

try block with except

When the critical statements in the try block raise an error, to handle that error and execute remaining part of the code we use except block. We can also know the type of error raised using exception in the except block.

Example

Following is an example of try block with except −

var1 = 9
var2 = 0
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 : integer division or modulo by zero
This block is executed irrespective to the error
python_keywords.htm
Advertisements