In Python, how to handle exceptions using the keywords try, except, and finally.
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 if not handled.
Why do we need exception handling? Exceptions are not the errors introduced intentionally, neither are they 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 subsequent request.
What try
, except
, and finally,
keywords do?
These are the keywords in Python for exception handling. Each keyword has its 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 when there is no exception.
try:
x = 6;
print(x/2);
except Exception:
print("Exception while division");
finally:
print("Execution Completed");
3.0
Execution Completed
Python code example – With the exception
try:
x = 6;
print(x/0);
except Exception:
print("Exception while division");
finally:
print("Execution Completed");
Exception while division
Execution Completed
How to Print The exception cause us to 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