Member-only story
Exception Handling in Python
A simplistic explanation of exception handling in python
In this article, we will understand:
- What is an exception, and how to handle exceptions in python?
- How to handle multiple built-in exceptions?
- How to create user-defined exceptions?

An exception is an error that occurs when your program is executing. When the exception occurs at the run time, it looks for an exception handler; if the exception handler does not exist, then your program stops abruptly. If the exception handler is present, then the code inside the exception handler is executed.

To handle exceptions, we use a try, except, and finally block.
Try and Except block in the exception handler
First, the code inside the try block is executed; if there are no errors, then the except block will be skipped.
If there are errors in the try block, then the rest of the code inside the try block is skipped. Control is passed onto the except block to handle the exception

try:
f= open("a.csv", "r")
data=f.read()
print(data)
except:
print("Some error")
If the file a.csv exists then, we get the contents of the file a.csv
If the file a.csv does not exist, then we get the message “Some error.” from the exception handler.
The finally block in the exception handler
The finally block is an optional clause in Exception Handler. It is used for any clean-up actions that need to be executed under any situation.
The finally block is executed in both the cases, successful execution of all the statements in the try block as well as when an exception occurs during the execution of the try block.