try with except in python by R4R Team

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")


output-

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


-In this program, we divide first number by second number, in case of second number is 0, it will execute the except part.

Multiple except block-

Syntax-

try:
block
except exception1:
block
except exception2:
block
.
.
.
expect exceptionn:
block

program-

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)


output-

Enter first number
6
Enter second number
1
List indicies must be integer but here n is float 6.0


If we do not pass any exception in except -

program-

try:
n=1/0
except:
print("Error")


output-

Error




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!