Python Exception Handling

Python Exception Handling

python exception handling is one of the concepts in python programming. Before start working with exceptional handling in python what is an exception ? An exception is an event which occurs while running the program which stops the program to work further. Exception also tells about the problem in the code execution. We can write our own exception. Some time if some exception is raised while running the program and we don't want our program to stop. what can we do ? we can handle it using syntax "try.....except....finally" in python.

Bult-in exceptions in python

We have many built-in exceptions in python, but most probable exceptions are

  • ImportError:
    >>> from collections import mycollecton
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ImportError: cannot import name 'mycollecton'
    
    It occurs when we try to import a function or class or any name from a module or a package then this exeption will be raised.
  • IndexError
    >>> my_list = [1,2,"Guido", "Batta"]
    >>> my_list[10]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    IndexError: list index out of range
    
    It occurs when we try to access an element in a list with an index which doesn't exists then this exceptions will be raised.
  • KeyError

    >>> my_dict = {"one": 1, "two": 2}
    >>> my_dict["three"]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 'three'
    
    It occurs when we try to access a key in the dictionary which does not exists then this exception will be raised.

  • NameError

    >>> my_name
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    NameError: name 'my_name' is not defined
    
    It occurs when we try to access a variable that is not defined then this exception will be raised

  • SyntaxError

    >>> if 10; print(100)
      File "<stdin>", line 1
        if 10; print(100)
             ^
    SyntaxError: invalid syntax
    
    It occurs when we try to run an invalid syntax then this exeption will be raised.

  • IndentationError

    >>> if True:
    ... print(10)
      File "<stdin>", line 2
        print(10)
            ^
    IndentationError: expected an indented block
    

It occurs when we try to write not indented code then this exception will be raised. We must follow indentation while writing the code. All built-in errors are child classes of BaseException class. We find more information on it in python documentation on exceptional handling.

Raising custom exception in python

Let's write an email validator that will raise an exception when an email is invalid.

class InvalidEmailException(Exception):
    pass
# lets raise it
import re
if not re.match(r"[^@]+@[^@]+\.[^@]+", "google.co.in"):
    raise InvalidEmailException

In above code we are raising our custom exception for invalid emails. "raise" is a keyword that is used to throw an exception in python. It will stops further execution of the program. This is how exceptions are used.

Handling exceptions in python

For handling exceptions we use try....except...finally clause in python. Let's see an example below

Case: write a function to return division of given numbers

def division(a, b):
    try:
        result = a / b
        print(result)
    except ZeroDivisionError:
        print("Can't devide with zero")
        result = 'Inf'
    finally:
        return result
# check the function with below tests
division(12, 2)
# 6.0
division(10, 0)
# Can't divide with zero

In above case we have handled "ZeroDivisionError" exception and returned the string 'Inf' for "division(10, 0)". We can do more with exception handling in python.

References:
https://docs.python.org/3/library/exceptions.html