Normally in Python, the exception is handled by the computer itself. But the exception which is thrown by the system compiler is not known by all. In order to throw some specific Error, we use exception handling. It has four main blocks which is explained as follows.
The first two main blocks are try and expect. The expect is followed by the Exception. The general syntax is,
try:
Statement_1
Statement-2
…..
expect exception_name:
Exception message
The try block is used to check the condition. If the condition fails, then expect block block is called with corresponding to the exception.
Example:-
a=4
b=0
try:
c=a/b
expect Exception:
print(“Division by zero Error”)
Output:-
Division by zero Error
The keyword Exception is commonly used exception in the python. The third block is else which is used when the try block is satisfied and further step has to be executed.
The fourth block is finally, which is called even when the try block does not throws an exception. Lets see an example which contains all these blocks.
Example:-
a=int(input(“Enter a”)
b=int(input(“Enter b”)
try:
c=a/b
expect Exception:
print(“Division by zero Error”)
else:
print(“The Divided Number is %d” % c)
finally:
print(“Finally block is called”)
Output 1 :-
Enter a 10
Enter b 5
The Divided Number is 2
Finally block is called
Output 2:-
Enter a 5
Enter b 0
Division by zero Error
Finally block is called