![]() |
VOOZH | about |
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting.
Example: In this code, The system can not divide the number with zero so an exception is raised.
Output
Traceback (most recent call last):
File "/home/8a10be6ca075391a8b174e0987a3e7f5.py", line 3, in <module>
print(a/b)
ZeroDivisionError: division by zerotry:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)Let’s first understand how the Python try and except works
Example: Let us try to take user integer input and throw the exception in except block.
Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero
Here's an example that demonstrates how to use multiple except clauses to handle different exceptions:
Output:
Enter a number: An error occurred: EOF when reading a line
The code enters the else block only if the try clause does not raise an exception.
Example: Else block will execute only when no exception occurs.
Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception. Even if you return in the except block still the finally block will execute
Example: Let's try to throw the exception in except block and Finally will execute either exception will generate or not
Output:
Yeah ! Your answer is : 1
This is always executed
Sorry ! You are dividing by zero
This is always executed