EXCEPTION HANDLING IN PYTHON
In this article, we will learn about exception handling in python by exploring try, except, else and finally statements. By knowing about how to handle exceptions, we can write better and neat code.
What is Error?
Error occurring is an unfortunate event in coding that happens when something in the code is not right. It could be a human mistake in coding structure or calculations. For Example:
a = 4 b = 2 if a < b print("a is less than b") else: print("b is less than a")
File "C:\Users\Hira\Desktop\Python Projects\Test\main.py", line 61 if a < b ^ SyntaxError: invalid syntax
What is Exception Handling in Python?
Before we jump into knowing about Exception Handling in Python, we must learn about why we need to handle exceptions in the first place. When you are coding in python or any other programming language, you are bound to have errors and some of those errors might terminate your whole program. But, what if, you as a developer is able to tackle those errors with exception handling methods? So yes! there are exception handling methods in python for developers to deal with recurring errors.
Try-Except Code Blocks
When you think that there are chances of having an error then you can use a try-except block to handle it. You can tell python what to ‘try’ and what not ‘except’ a certain exception. For example:
try: print(10/0) except ZeroDivisionError: print("You had a zero error")
You had a zero error
You can use exceptions to prevent programs from crashing. This is very reason why we need exceptions in the first place.
Let’s look at a quick example of the zero exception error that happens when a number is divided by 0.
It’s impossible to do so, see below:
Traceback (most recent call last): File "C:\Users\Hira\Desktop\Python Projects\Test\main.py", line 1, in print(10/0) ZeroDivisionError: division by zero
Above, you can see that there is a ZeroDivisionError: division by zero, python stops the program right there unless we put an exception to prepare ourselves for this kind of error.
When we are working with files, it is very common to have missing files issues. This may occur due to a different storage location of the file or maybe you have misspelled the file name or the file may not exist at all. Let’s try an example and read a file named ‘popeye.txt’. Now the below program is trying to read the file ‘popeye.txt’ but since we haven’t saved the file let’s see what happens:
f = open("popeye.txt") print(f.read())
Traceback (most recent call last): File "C:\Users\Hira\Desktop\Python Projects\Test\main.py", line 57, in f = open("popeye.txt") FileNotFoundError: [Errno 2] No such file or directory: 'popeye.txt'
The output reports a FileNotFoundError exception. To minimize this exception, the try-except block will be useful so that the program doesn’t generate any error.
try: f = open("popeye.txt") print(f.read()) except FileNotFoundError: print("Sorry, File doesn't exist")
Sorry, File doesn't exist
To make more sense of the try-except block, we can introduce an else statement with it as well to or calculate the answer if the given condition is met otherwise. For Example:
x = 10
y = 0
result = x/y
print("You have a zero division error")
After trying out
try-except-else blocks, it is time to learn about the
finally block. This block will always execute no matter whether try turns out to be true or false. For Example:
x = 10 y = 0 try: result = x/y except ZeroDivisionError: print("You have a zero division error") else: print(result) finally: print("The exception handling is finished")
You have a zero division error The exception handling is finished
Here is a list of more python built-in-exceptions that can help you minimize errors in your programs. Check out more on Python Exceptions Docs
|Raised when the assert statement fails.
|Raised on the attribute assignment or reference fails.
|Raised when the input() function hits the end-of-file condition.
|Raised when a floating point operation fails.
|Raised when a generator’s close() method is called.
|Raised when the imported module is not found.
|Raised when the index of a sequence is out of range.
|Raised when a key is not found in a dictionary.
|Raised when the user hits the interrupt key (Ctrl+c or delete).
|Raised when an operation runs out of memory.
|Raised when a variable is not found in the local or global scope.
|Raised by abstract methods.
|Raised when a system operation causes a system-related error.
|Raised when the result of an arithmetic operation is too large to be represented.
|Raised when a weak reference proxy is used to access a garbage collected referent.
|Raised when an error does not fall under any other category.
|Raised by the next() function to indicate that there is no further item to be returned by the iterator.
|Raised by the parser when a syntax error is encountered.
|Raised when there is an incorrect indentation.
|Raised when the indentation consists of inconsistent tabs and spaces.
|Raised when the interpreter detects internal error.
|Raised by the sys.exit() function.
|Raised when a function or operation is applied to an object of an incorrect type.
|Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
|Raised when a Unicode-related encoding or decoding error occurs.
|Raised when a Unicode-related error occurs during encoding.
|Raised when a Unicode-related error occurs during decoding.
|Raised when a Unicode-related error occurs during translation.
|Raised when a function gets an argument of correct type but improper value.
|Raised when the second operand of a division or module operation is zero.