except clause to handle the exception or exceptions. For example, in our earlier example, we can use the try and except clause to handle the ZeroDivisionError exception.
n = 100
m = 0
try:
r = n/m
print(r)
except ZeroDivisionError:
print("Dividing a number by zero")
The above program will terminate normally and print the following output:
Dividing a number by zero
Now, let’s say a block of statements is put within a try clause. And, the block of statements can raise a number of exceptions. In that case, we can use multiple except clauses for a single try clause.
n = 100
m = 1
try:
r = n/m
print(rr)
except ZeroDivisionError:
print("Dividing a number by zero")
except NameError:
print("Variable is not defined")
Here, we are trying to print the variable “rr” that is not defined. As a result, the program will throw a NameError exception and the program will print the following output:
Variable is not defined
Now, let’s say we are trying to open a file and write something in it. An exception may be raised while opening the file as well as when writing to the file. We can handle the exceptions in the following way:
try:
f = open("abc.txt", "r")
try:
f.write("Hello")
except:
print("Something went wrong while writing to the file")
finally:
f.close()
except FileNotFoundError:
print("File not found")
except FileExistsError:
print("File exists")
Here, the “except:” clause will match any exception that is thrown at the time of writing to the file. And, the finally clause will be executed after the except clause is executed. In the finally clause we are closing the file so that the file does not …








































0 Comments