Python Exception Handling: Try, Except, and Finally in Python
This article on python exception handling will help you brush up on your knowledge of the topic so that you can excel in your next python job interview or exam.
Join the DZone community and get the full member experience.Join For Free
There are two types of error in python, i.e., Exception and Syntax error. Errors are the problems that occur in the program, and the execution of the program will stop due to this error. And on the other hand, if we will talk about exceptions when the normal program is disturbed due to some internal event, then the exception is raised in the program.
Difference Between Syntax Error and Exceptions
As its name suggests that the error occurred due to the written wrong syntax in the code, which is called a syntax error. And the program will be terminated due to the syntax error.
Example: Here, in the above lines of code, ":" is not used after the if statement, then it will result in a syntax error in the program.
# taking one variable and initializing its value var = 500 # check the value of the variable is greater than the 100 if(var>100) print("Value of the variable is greater than 100") else: print("Value of the variable is not greater than 100")
File "main.py", line 4 if(var>100) ^ SyntaxError: invalid syntax
When the code of the program is correct syntactically, but the execution of the code results in an error, then it is known as an exception. The execution of the program is not stopped by these exceptions. Instead of stopping the program execution, exceptions will disturb the normal program flow.
# taking one variable and initializing its value var = 500 # trying to divide the variable with zero a = var / 0 # printing the value of a print(a)
Traceback (most recent call last): File "main.py", line 4, in <module> a = var / 0 ZeroDivisionError: division by zero
In the above-given code, an exception named ZeroDivisionError is raised as in the above code, we are trying to divide a number with the zero.
Exception handling is the procedure of responding to unexpected or unwanted events occurring at the time of execution of a program. These events are dealt with by exception handling so that there is no system crashing, and Normal programs will be disrupted by the exception if the exception handling is not used.
The exception can occur in the program due to many reasons, such as failure of the device, the user trying to enter invalid input, network connection list, errors in the code, sufficient memory not available for program execution, the user trying to open the files that are not available or there is an operation in a program that tries to divide the number by zero.
In python, for all exceptions, the Exception is the base class.
Try and Except Statement: Catching Exceptions
In python, to catch and handle the exception, try and except keywords are used.
Try block contains a statement or set of statements that will raise any exception in the program. The except block will be skipped if no exception occurs at the time of execution of try block statements. All the statements in the try block are to be written indented.
If the exception occurs while executing the statements of the try block, then program control is transferred to the except block.
Except contains the set of statements that are for handling the exception that has occurred in the execution of try block statements. Forex: printing error message at the time of the exception. And the statements of except will also be written indented.
And after the except keyword, the exception type can also be specified. But that block will be executed only at the time of occurrence of the specified exception. Multiple except blocks with different specified exceptions can also be there with the single try block.
If the exception occurring in the try block statements does not match with any of the specified except block exceptions, then the exception in the program will be terminated, and that exception remains unhandled.
Example 1: Let us write the program in which we are declaring an array, and we are trying to access the element of that array that is out of the bond. This exception is handled in the below code using the except block.
# Simple python program example for handling the runtime error # declaring an array with three elements ar = [1, 2, 3] # try block try: # using 0 index to access and print the first element of the array print ("First element stored in array = %d" %(ar)) # using 4 index to access and print the fifth element of the array print ("Fifth element stored in array = %d" %(ar)) # above statement will raise an error as there are only three elements in the array # except block except: # set of statements that will handle the exception print ("An error occurred in the program")
First element stored in array = 2 An error occurred in the program
In the above lines of code, the try block contains the set statement in which there are chances of the exception occurring (in the above code, the second print statement of the code).
The second print statement is trying to access and print the fifth element of the array arr, which does not exist as the size of the array is three, so only till the third element can be accessed. And the statements written in the except block will be executed after the exception.
Example 2: Here, we are initializing the value of two variables one is an integer value, and the other is with string value data type, and an exception will occur when we try to add both values.
# declaring a variable with an integer value a=5 # declaring a variable with the string value b="0" # try block try: # Exception is occurred as trying to add integer and string print (a+b) # except block except: print('An error occurred in the program')
An error occurred in the program
Catching Specific Exception
For the specification of different exception handlers, more than one exception block is allowed with the single try block. For example, IndexError, and DivideByZero exceptions handler can be written with the except keyword.
But one block statement will be executed among all the except statements at most. And for adding the specific exception general syntax is given below:
try: # set of statement(s) except IndexError: # set of statement(s) except ValueError: # set of statement(s) Example: Catching specific exceptions in Python # declaring a variable with the integer value a=5 # declaring another variable with the integer value b=0 try: # trying to divide both values print (a/b) # exception will occur as we are trying to divide a # number by zero # except block to handle TypeError exception except TypeError: print('Operation is not supported') # except block to handle ZeroDivisionError exception except ZeroDivisionError: print ('Divide a number by zero is not allowed')
Divide a number by zero is not allowed
Try With Else Clause
Python also allows the use of one of the control flow statements, the else keyword, with try-except. A set of statements written in the else block will be executed only when there is no exception at the time of trying block statements.
The else block will be written after all the except blocks. The statements of the else block will also be written indented. Else block with try-except syntax is given below:
try: # Set of statements... except: # optional block # block to write code to handle the exception else: # set of statements to be executed if no exception is # occurred in the try block Example: Try with the else clause # python to demonstrate the else clause with try-except # declaring a variable with an integer value a=10 # declaring another variable with an integer value b=5 # try block try: # trying to divide both values print (a/b) # except block except: print('An error occurred) # else block else: print('Inside else block')
2.0 Inside else block
Finally, Keywords in Python
Python also allows the use of the final keyword in exception handling. The set of statements will always be executed whether the try block is terminated normally or the try block is terminated due to an exception.
Finally, the block is always written after all the except blocks. Finally, block syntax is given below:
Syntax: try: # Set of statements... except: # optional block # block to write code to handle the exception else: # set of statements to be executed if no exception is # occurred in the try block finally: # always executed # set of statement Example: # Python program to show the example of finally # try block try: # divide by zero exception will occur a = 5/0 print(a) # block of code to handle divide by zero exception except ZeroDivisionError: print("An error occurred") finally: # block of code executed always whether there is # exception occurred or not print('Finally block!! Executed Always')
An error occurred Finally block!! Executed Always
In python, the raise keyword is used in exception handling for forcing some exceptions to occur in the program. The argument of the raise statement specifies the exception to be raised. And we can specify any exception class or an exception instance here.
# Python program to demonstrate the example of raising Exception # try block try: # raising a named exception raise NameError("Hello!!") # except block which will catch the raised NameError except NameError: print ("An exception") # again raising an exception and this will not be handled by the catch block raise
The output of the above line of code first prints “An exception,” then the run time error is displayed in the output on the console as the raise keyword is used in the last line, which will raise an error. The output of the above line of code displayed on the console is given below:
An exception Traceback (most recent call last): File "main.py", line 5, in <module> raise NameError("Hello!!") NameError: Hello!!
Hope this small guide on Python Exception handling helped you grasp the basics of exception handling. Although this is a quite basic topic, save this article for brushing up your knowledge on the same just before your next python job interview or exam, as this is a most commonly asked topic! Thanks for reading.
Opinions expressed by DZone contributors are their own.