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")

Output is:

  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. Exception Handling in Python


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")

Output is:

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.


ZeroDivision Exception

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:

print(10/0)

Output is:

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.





FileNotFoundError Exception

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())

Output is:

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")

Output is:

Sorry, File doesn't exist




Else Block

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 try: result = x/y except ZeroDivisionError: print("You have a zero division error") else: print(result)

Finally Exception

After trying out try-except and 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")

Output is:

You have a zero division error
The exception handling is finished




More Built-in-Exceptions

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

Exception Description
AssertionError Raised when the assert statement fails.
AttributeError Raised on the attribute assignment or reference fails.
EOFError Raised when the input() function hits the end-of-file condition.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raised when a generator’s close() method is called.
ImportError Raised when the imported module is not found.
IndexError Raised when the index of a sequence is out of range.
KeyError Raised when a key is not found in a dictionary.
KeyboardInterrupt Raised when the user hits the interrupt key (Ctrl+c or delete).
MemoryError Raised when an operation runs out of memory.
NameError Raised when a variable is not found in the local or global scope.
NotImplementedError Raised by abstract methods.
OSError Raised when a system operation causes a system-related error.
OverflowError Raised when the result of an arithmetic operation is too large to be represented.
ReferenceError Raised when a weak reference proxy is used to access a garbage collected referent.
RuntimeError Raised when an error does not fall under any other category.
StopIteration Raised by the next() function to indicate that there is no further item to be returned by the iterator.
SyntaxError Raised by the parser when a syntax error is encountered.
IndentationError Raised when there is an incorrect indentation.
TabError Raised when the indentation consists of inconsistent tabs and spaces.
SystemError Raised when the interpreter detects internal error.
SystemExit Raised by the sys.exit() function.
TypeError Raised when a function or operation is applied to an object of an incorrect type.
UnboundLocalError Raised when a reference is made to a local variable in a function or method, but no value has been bound to that variable.
UnicodeError Raised when a Unicode-related encoding or decoding error occurs.
UnicodeEncodeError Raised when a Unicode-related error occurs during encoding.
UnicodeDecodeError Raised when a Unicode-related error occurs during decoding.
UnicodeTranslateError Raised when a Unicode-related error occurs during translation.
ValueError Raised when a function gets an argument of correct type but improper value.
ZeroDivisionError Raised when the second operand of a division or module operation is zero.