Advertisement
# Python - try-except block
a,b= 10,0
try:
c=a/b # If a is divided by b(which has a value 0)
print("The result of a/b is : ", c)
except ZeroDivisionError: # A matching type of exception is declared in except block
print("An exception is caught") # A message related to caught exception is printed in except block
print("Outside try-except block")
An exception is caught
Outside try-except block
Advertisement
# Python - try-except blocks example
a,b= 10,0
try:
c=a/b # If a is divided by b(which has a value 0)
print("The result of a/b is : ", c)
except ZeroDivisionError as arg: # An except block is declared with the as keyword
print("An exception caught : ",arg) # A message related to caught exception is printed
print("Outside try-except block")
An exception caught : division by zero
Outside try-except block
class TryCatch2:
def meth(self):
try:
print(100/0); #ZeroDivisionError exception is raised here
print("Hello from meth function")
except IOError : #Non-matching exception-type is declared with this except statement
print("We have caught an exception")
print("Outside try-except blocks")
ob = TryCatch2()
try:
ob.meth() #enclosing the call to meth() method in try block
except ZeroDivisionError as e:
print("An exception is caught - ", e)
An exception is caught - division by zero
try:
f = open("File.txt", 'w');
f.write('Hello there from DecodeJava')
print("Statement between try-except"); #This statement is outside the try block statements as it is not indented
except Exception :
print("An exception is caught")
try:
f = open('File.txt','w')
f.write('Hello there')
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement