As discussed in the previous article, Exceptions can be defined as an output event raised to the calling function when there is a runtime error.
In Python, exceptions are raised when the program encounters an error or we can say when something in the program goes wrong.
Whenever these exceptions occur, the Python interpreter terminates the current process and passes it to the calling process until it is handled. If not handled, the program will crash.
And the process of handling the exceptions in a graceful way such that we control the output and the flow of the program even in case of such exceptions is known as exception handling.
We use a combination of try, except, else, and/or finally blocks to control the flow of the program and handle the exceptions that we will discuss further in detail.
2. How does Try-Except works in Python
In python, we use try and except block for catching and handling the exception. The try block takes the codes inside it as a normal part of its program. Whereas, the except block takes the codes inside it as a response for exception which has arisen in the above try clause.
There can be multiple except blocks after a try statement. These except blocks are handled sequentially and the first except block that can handle the error will be executed.
In case of no error, the except block is skipped and is not executed.
We can specify which exceptions an except clause should catch. If an except block expects Exception or does not specify any exception then this block will handle all the exceptions. For example
# do something
# handle all exceptions
A try clause can have any number of except clauses to handle different exceptions, however, only one will be executed in case an exception occurs.
We may pass multiple exceptions in one except clause by providing all values as a parenthesized tuple.
Let’s take an example to understand the working of try-except blocks.
list_1 = [10, 9, 8, 7]
print("First element in the list is= %d" %(list_1)
print("second element in the list is= %d" %(list_1)
print("Fourth element in the list is= %d" %(list_1)
print("Fifth element in the list is= %d" %(list_1) #Throws error
print("Exceeded Out of Limit.")
First element in the list is= 10
second element in the list is= 9
Fourth element in the list is= 7
Exceeded Out of Limit.
val = 19
if val < 40 :
result = val/(val-19) # throws ZeroDivisionError
if val >= 15:
print("Result is = ", result) # throws NameError
print ("\nError Present but Resolved")
Error Present but Resolved
3. Python try with else block
In certain situations, we might want to run a specific logic only if there is no error in the try block and for such purpose, we use the else block.
In python, we use else clause on the try-except block after writing all except clauses. The codes in the else block will execute only when the try clause does not raise an exception.
print("Greetings for the day.")
print("We are sorry.")
Let’s understand it with a real example. In this example, if the calculation results in ZeroDivisionError then except block handles it otherwise else block executes.
In python, we have the finally keyword which is placed after the try and except blocks. finally block is always executed and it dooes not depend whether the try block has been executed normally or throws some exception.