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 we need exception handling? Exceptions are not the errors put intentionally, neither they are validations. These are the scenarios that are not processed for the given data.
For example, while writing a function in a server program you forgot to put a validation of zero value for the divisor in a user-defined division function. All works well but, what if there is zero? The program will crash and the server needs to start again if no exception handling. Not a good practice at all.
With exception handling, server will not stop and a user can show a message and read next request.
What try, except, and finally does?
These are the keywords in python for exception handling. Each keyword has its own code bock. A try block contains the actual programmer code. The execution reaches the except where there is an exception in the try block and finally 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