Exception Handling in Python
This article will walk you through the process of exception handling in Python with the “try”, “except” and “finally” statements, along with some useful examples.
There are two different kinds of problems that can occur in Python: Syntax errors and exceptions. Errors are difficulties that occur within a program and are the reason why the program will halt its execution when an error occurs. On the other hand, exceptions arise if a normal flow of the program is disrupted by certain happenings within the program itself.
The Difference between Exceptions and Syntax Errors
Error in Syntax: As its name suggests, incorrect syntax caused this type of error anywhere inside the code. It ultimately results in the conclusion of the program.
# initialize the amount variable amount = 10000 # check that You are eligible to # purchase Dsa Self Paced or not if(amount > 2999) print("You are eligible to purchase Dsa Self Paced")
Exceptions: An exception takes place whenever a program is syntactically correct but the code produced an error. Exceptions raise when a program’s syntax is proper but the code produces an error. Although the error does not halt the execution of the program, the usual flow of the program is disrupted.
# initialize the amount variable marks = 10000 # perform division with 0 a = marks / 0 print(a)
The above example resulted in the generation of a ZeroDivisionError since we attempted to divide a number by 0. Note that the Exception class serves as the foundation for all exceptions in Python.
Try and Except Statement – Catching Exceptions.
In Python, the “try” and “except” commands are responsible for catching and handling exceptions. The “try” clause includes the statements that have the potential to throw an exception whereas the statements responsible for handling the exception are written within the except clause.
Example: Let’s attempt to access the array member whose index is outside the allowed range. Then we deal with the exception that results from doing so:
# Python program to handle simple runtime error #Python 3 a = [1, 2, 3] try: print ("Second element = %d" %(a)) # Throws error since there are only 3 elements in array print ("Fourth element = %d" %(a)) except: print ("An error occurred")
The statements that have the potential to generate an error are in the “try” statement in the preceding illustration (second print statement in our case). An exception occurs as a result of the fact that the second print statement attempts to access the fourth element of the list, which does not exist. Unless statement will then take care of this unforeseen circumstance.
Errors vs Exceptions
During the course of the execution of a program, undesirable events known as errors and exceptions can occur. However, there are significant distinctions between the two. The programmer can prepare for and anticipate exceptions, but it is much more difficult to prepare for and anticipate errors. Exceptions can either have their checkboxes ticked or left unchecked. However, errors are never checked for or eliminated. Exceptions are almost always an indication that the programmer has made a mistake.
On the other hand, errors might occur by a malfunction in the system itself or by the incorrect utilization of a resource. Consequently, handling exceptions should be done at the application level, while handling errors should be done at the system level (only if possible). As soon as you have dealt with an exception, you are certain to return to the normal flow of the application. However, even if the programmer discovers a mistake, he might not be aware of how to deal with it in the first place. Unlike more conventional methods of error management, exceptions make it possible to keep error-handling code distinct from other types of code.
Python comes with a term called “finally” that is always performed after the try and except blocks have been completed. The final block will always execute after the “try” block has finished or after the “try” block has finished executing owing to an exception.
try: # Some Code.... except: # optional block # Handling of exception (if required) else: # execute if no exception finally: # Some code .....(always executed)