Exception handling in Python with try, except, and finally keywords.
The try, except, and finally are the keywords in Python for exception handling. An exception is a runtime error, that causes the program to stop.
Why do we need exception handling? Exceptions are not the errors introduced intentionally, neither they are validation checks. An exception occurs if a program can not process the given data values.
For example, while writing a division function in a server program you forgot to put a validation of zero value for the divisor.
All works well until the divisor is non-zero. What if it is zero? If the program does not handle this exception, the program will crash and the server needs to start again. Not a good practice at all.
With exception handling, the server program will not stop and a user can print a message and read the next request.
What try, except, and finally keywords do?
These are the keywords in python for exception handling. Each keyword has its own associated block of code. A try block contains the actual programmer’s code. The execution reaches the except where there is an exception in the try block and the code within the finally block always executes.
try: #User application code except Exception: #Executes upon exception finally: #Always executes
Python code example – No exception – Division by zero
try: x = 6; print(x/2); except Exception: print("Exception while division"); finally: print("Execution Completed");
3.0 Execution Completed
Python code example – With exception
try: x = 6; print(x/0); except Exception: print("Exception while division"); finally: print("Execution Completed");
Exception while division Execution Completed
Print The exception – Know what exactly error where there could be multiple exceptions-
try: x = 6; print(x/0); except Exception as e: print('Exception :', e); finally: print("Execution Completed");
Exception : division by zero Execution Completed