Python try...except

 

Python try...except

try….. except blocks are used in python to handle errors and exceptions. The code in try block runs when there is no error. If the try block catches the error, then the except block is executed. 

 

Example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")

 

Output 1:

Enter an integer: 6.022
Number entered is not an integer.

Output 2:

Enter an integer: -8.5
Number entered is not an integer.

Output 3:

Enter an integer: -36

 

In addition to try and except blocks, we also have else and finally blocks.

The code in else block is executed when there is no error in try block.

 

Example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")
else:
    print("Integer Accepted.")

 

Output 1:

Enter an integer: 69
Integer Accepted.

Output 2:

Enter an integer: -2.3
Number entered is not an integer.

 

The finally block is execute whatever is the outcome of try……except…..else blocks.

Example:

try:
    num = int(input("Enter an integer: "))
except ValueError:
    print("Number entered is not an integer.")
else:
    print("Integer Accepted.")
finally:
    print("This block is always executed.")

 

Output 1:

Enter an integer: 19
Integer Accepted.
This block is always executed.

Output 2:

Enter an integer: 3.142
Number entered is not an integer.
This block is always executed.