Try-
-Try block is a block in which we write that part of program where chances of exception will occur.
Except-
- Except is a part where we handle the generated exceptions or this block is run after the exception generate.
syntax-
try:
block1
except exceptionname:
block2
-Here block1 is a part of program where chance of exception occur will more.
-And block2 is a part which execute after the exception occur.
program-
n=int(input("Enter first numbern"))
try:
n=n/int(input("Enter second numbern"))
print(n)
except ZeroDivisionError:
print("Second number is 0 , which give an error on division")
Enter first number
6
Enter second number
3
2.0
Enter first number
6
Enter second number
0
Second number is 0 , which give an error on division
n=int(input("Enter first numbern"))
try:
n=n/int(input("Enter second numbern"))
l=[1,2,3,4]
print(l[n])
except ZeroDivisionError:
print("Second number is 0 , which give an error on division")
except IndexError:
print("list index is out of index")
except TypeError:
print("List indicies must be integer but here n is float",n)
Enter first number
6
Enter second number
1
List indicies must be integer but here n is float 6.0
try:
n=1/0
except:
print("Error")
Error