How to use Python try except finally
Python provides us with the functionality to handle run-time errors in the program. These errors are also called exceptions. Exceptions occur when a program fails to execute a particular statement. In this Answer, we will explore how we can handle exceptions in the code and what happens if we do not handle exceptions or errors correctly.
Uncaught exceptions
Using the following coding example, let's get an idea of what happens if we do not handle exceptions or errors in our code. Please click "Run" to execute the code below:
print("Welcome")print("to")print(educative)print("This line does not print because the program crashes on the previous statement")
We can see the code explanation below:
Line 3: We forcefully create an error by printing
educativewithout converting it to a string ( i.e.,"educative").educativeis being dealt with as a variable instead of a string which causes the program to crash as no variable with the nameeducativeis defined in the program. The program halts and raises an exception. As the exception is not handled, the code after line 3 does not execute, and our program crashes.
Handling exceptions
Handling exceptions is an essential part of writing programs and creating applications. Imagine if we have a large-scale application and an error occurs while running. This will cause the whole application to crash. Therefore, Python provides us with try exceptelsefinallytry and except can be seen by clicking the "Run" button below:
print("Welcome")print("to")try:print(educative)except:passprint("The program kept on executing because we handled the exception")
In the code above, the execution continues even when the error occurs at line 4. In line 6, we use the pass statement. It is a null operation statement used as a placeholder for code blocks where no action is needed.
Coding example
We will see coding examples showing the use of try, except, else, and finally blocks in error handling.
try block without error
Please click the "Run" button below to execute the code:
try:print("Try block executing")except:print("Error occurred in the try block")else:print("Else block exectuing")finally:print("Finally block always runs")
The code explanation is given below:
Lines 1–2: We create
tryblock with a simpleprintstatement of"Try block executing".Lines 3–4: We create
exceptblock with aprintstatement"Error occured in the try block". As there is no error in thetryblock, theexceptblock does not execute.Lines 5–6: We create the
elseblock with theprintstatement"Else block executing". We see this statement in the console as there was no error in thetryblock. Theelseblock was executed.Lines 7–8: We create the
finallyblock that prints the statement"Finally block always runs". We see this statement in the console because thefinallyblock executes every time.
try block with error
In the previous example, we saw how the try, except, else, and finally blocks execute if there is no error in the try block. In the following example, we will see what happens if an error occurs in the try block.
Please click the "Run" button to see the code in action:
try:print(Try)except:print("Error occurred in the try block")else:print("Else block exectuing")finally:print("Finally block always runs")
We can see the code explanation below:
Lines 1–2: We generate an error in the
printstatement as no variable namedTryis in the code.Lines 3–4: The
exceptblock runs as an error is generated in thetryblock. We see"Error occurred in the try block"in the output box.Lines 5–6: We see that the
elseblock does not execute.Lines 7–8: The
finallyblock executes every time, regardless of whether an error occurs or not.
Conclusions
By utilizing try, except, else, and finally blocks in Python, we can easily handle exceptions in the program. This helps us make the programs robust by controlling the programs in case of success and failure.
Free Resources