Python exception handling using try except with examples
Example 1:
try:
===>number = int(input("Enter a number: "))
===>print(number)
except:
===>print("Invalid Number")
First Result:
Enter a number: 9
9
Second Result:
Enter a number: no
Invalid Number
Example 2:
try:
===>calculation = 50/0
===>number = int(input("Enter a number: "))
===>print(number)
except ZeroDivisionError:
===>print("Divided by Zero related EXCEPTION")
except ValueError:
===>print("Invalid Input related EXCEPTION")
Result:
Divided by Zero related EXCEPTION
Example 3:
try:
===>calculation = 50/0
===>number = int(input("Enter a number: "))
===>print(number)
except ZeroDivisionError as err:
===>print(err)
except ValueError:
===>print("Invalid Input related EXCEPTION")
Result:
division by zero