Python exceptions

what is exception?

  • Errors detected during execution are called exceptions.

when to raise exceptions?

  • when the unexpected input recieved
  • when unable to proceed further with the given input

python keywords for exceptions

  • raise - used to throw new exception
  • try - used to test the code which may throw an error
  • except - used to catch the exception/error to handle it
  • else - used to execute code when there is no error
  • finally - used to execute the code regardless of the result of the try and except

how to raise an exeption?

  • pythons base exception class Exception is used to throw an exception.
  • let's look at an example
def math_div(num1, num2):
    if num2 == 0:
        raise Exception("Can't devide with zero")
    return num1 / num2
  • above program used to perform the division of two numbers.
  • division with zero can't be performed so, throwing an error.
  • let's call the funciton with some inputs
output = math_div(10,2)
  • above code gives output as 5
  • let's look at other input
output = math_div(10, 0)
  • above code gives the output looks like below
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in math_div
Exception: Can't devide with zero

most common in-built exceptions

  • Exception - base class for all user defined classes
  • AttributeError - accessed attribute does not found
  • EOFError - nothing to read from file
  • ImportError - failed to import a variable/function/module
  • IndexError - sequence subscript is out of range.
  • KeyError - mapping key is not found
  • NameError - a local or global name is not found
  • SyntaxError - syntax is invalid
  • IndentationError - inconsistent indentation
  • ValueError - operation or function receives an argument that has the right type but an inappropriate value

Read more about built-in exceptions at python official docs

how to handle raised exceptions?

  • use try and except keywords to handle the exception
import random

def get_random_number():
    return random.randint(0, 3)

try:
    lucky_num = 100 / get_random_number()
except ZeroDivisionError:
    print("Cant devide with zero")
else:
    print("you are very lucky")
finally:
    print("done")
  • if get_random_number() function returns 0 then it gives below output
Cant devide with zero
done
  • otherwise, it gives below output
you are very lucky
done

Note: else and finally are optional blocks

writing custom exceptions

  • let's write a function to read the file if file not found then raise a custom file not found exception.
import os

class FileNotFoundError(Exception):
    pass

def read_file(file_path):
    if not os.path.exists(file_path):
        raise FileNotFoundError("File does not exists")
    with open(file_path, 'r') as _file:
        return _file.read()

valid_file_path = "/tmp/users.csv"
invalid_file_path = "/tmp/no_file.csv"

print(read_file(valid_file_path))
print(read_file(invalid_file_path))

It gives output as below

John, K
Anji, B

FileNotFoundError: File does not exists

References