After reading this Python Try Except topic, you will know its theory, examples and, you will understand Try-Many-Excepts, Try-Except-Else & Try-Except-Finally in Python.
In the beginning, statements within try block execute and if any exception occurs, program execution jumps to except block statements and start executes them.
Example:
Program (1): To explain Try except based logic in Python.
try: val = int(input("Please enter any integer integer: ")) print('The integer value is', val) except: print('any error occur')
Output(1)
Please enter any integer integer: 23 The integer value is 23
Explanation:
- Statements within try block execute because the entered integer is 23.
Let us again execute the above program for the float value and see the result.
Output(1)
Please enter any integer integer: 23.5 any error occur
Explanation:
- Statements within except block execute because the entered value is a float.
Try with Many Excepts
try: print('The integer value is', val) except NameError: print('Variable var not defined') except: print('any error occur')
Output(1)
Variable var not defined
Explanation: for Program(1) and Output(1)
- Statements within except NameError block executes because entered integer is 23.
Try Except with Else
We can add else with try except. Here, else block statements executes if try statements do not give any error.
try: val = int(input("Please enter any integer integer: ")) print('The integer value is', val) except: print('enter value is not correct') else: print('the integer value as shown above')
Output(1)
Please enter any integer integer: 23 The integer value is 23 the integer value as shown above
Explanation: for Program(1) and Output(1)
- Statements within try block and else block executes because the entered integer is 23.
Let us again execute the above program and see the result.
Output(1)
Please enter any integer integer: 23.5 enter value is not correct
Explanation: for Program(1) and Output(1)
- Statements within except block execute because entered value 23.5 is a float.
Try Except with Finally
Here, statements within finally block execute always irrespective of the try block give an error or not.
Consider the statements in python is given by
try: val = int(input("Please enter any integer integer: ")) print('The integer value is', val) except: print('enter value is not correct') finally: print('Your result shown above')
Output(1)
Please enter any integer integer: 23 The integer value is 23 Your result shown above
Explanation: for Program(1) and Output(1)
- Statements within try block and finally block executes because the entered integer is 23.
Let us again execute the above program and see the result.
Output(1)
Please enter any integer integer: 23.2 enter value is not correct Your result shown above
Explanation: for Program(1) and Output(1)
- Statements within except block and finally block executes because entered value float is 23.2.