In our previous tutorial, we discussed about Python Directory. In this tutorial, we are going to learn Python Exception Handling. Python try except keywords are used for exception handling in python.
Table of Contents
Python Exception Handling
Basically, exception means something that is not expected. In real life, we are not interested to deal with exceptions. So there goes a proverb, “Exception is not an example”. But when we write programs, we have to think about exceptional cases. For example, if your user entered a string object while you were expecting an integer object as input, it will raise an exception.
Exception hampers normal program flows. If any exception happens, the programmer needs to handle that. Therefore, we are going to learn exception handling in upcoming sections.
Some Built-in Python Exceptions
List of some built-in python exceptions are given below.
- Exception : This is the base class for all kind of the exceptions. All kind of exceptions should be derived from this class
- ArithmeticError : This is the base class for the exception raised for any arithmetic errors.
- EOFError : This exception raise when input() function read End-of-File without reading any data.
- ZeroDivisionError : This exception raise when the second argument of a division or modulo operation is zero
- AssertionError : This exception raise when an assert statement fails.
- FloatingPointError : This exception raise when a floating point operation fails.
- KeyError : This exception raise when a mapping (dictionary) key is not found in the set of existing keys.
- KeyboardInterrupt : This exception raise when the user hits the interrupt key (normally Control-C or Delete). During execution, a check for interrupts is made regularly.
Besides, you can find the list of all Built-in Exception in their official site.
Python try except
While writing the code, some statements might suspicious for raising an error. Hence, those statements should be surrounded with a try-except-else block. For example, we will now raise an exception by our code. The following code will raise
name = 'Imtiaz Abedin' print(name) print('This will not print')
If you try running the code, you will get below exception.
Traceback (most recent call last): File "/home/imtiaz/ExceptionHandling.py", line 2, in print(name) IndexError: string index out of range
Because the size of the string type object ‘name’ is less than 15 and we are trying to access the index no 15. Have a look, the second print statement is not executed for that exception. So program crashes due to an exception. So, in the next code, we will handle this exception.
name = 'Imtiaz Abedin' try: print(name) except IndexError: print('IndexError has been found!') print('This will be printed print.')
So, you can see from the above two examples that exception should be handled to avoid the program crash. In our first example, the last print statement was not executed because the program found exception before that. You can see that try except keywords are used for exception handling.
Basic Structure of Python Exception Handling
In the previous section, we demonstrate how exception raised and how to handle that. In this section, we will discuss the basic coding structure for handling exceptions. Therefore, the basic coding structure for Python Exception Handling is given below.
name = 'Imtiaz Abedin' try: # Write the suspicious block of code print(name) except AssertionError: # Catch a single exception # This block will be executed if exception A is caught print('AssertionError') except (EnvironmentError, SyntaxError, NameError) as E: # catch multiple exception # This block will be executed if any of the exception B, C or D is caught print(E) except : print('Exception') # This block will be executed if any other exception other than A, B, C or D is caught else: # If no exception is caught, this block will be executed pass finally: # This block will be executed and it is a must! pass # this line is not related to the try-except block print('This will be printed.')
Here you can see that, we use
except keyword in different style. The first except keyword is used to catch only one exception that is
However, the second except keyword is used to catch multiple exceptions, as you see.
If you use except keyword without mentioning any specific exception, it will catch any exception that is raised by the program.
The else block will be executed if no exception is found. Lastly, whether any exception is caught or not, the
finally block will be executed.
So, if you run the above code, we will get the output:
If you change ‘name’ to ‘nameee’ in the above code, you will get the following output.
Python Exception Handling Important Points
For undergoing a professional python project you need to be careful about exceptions. A simple exception can ruin your code. So, you need to handle those exceptions. A few important points about handling exceptions are given below.
- It is better to surround the suspicious code with try-except.
- Using one try-except block for one line of suspicious code is better than using one try-except block for a block of suspicious code.
- It is better to catch specific exception class. Using generalized exception class is not that much useful for handling.
So, that’s all for Python Exception Handling. Hope, that you understand well. For any query, please use the comment box. We will answer you.