#Day14 - Exceptions in Python

rahulbanerjee99

Rahul Banerjee

Posted on April 4, 2021

#Day14 - Exceptions in Python

Today we will we talking about the Built-in Exceptions in Python.

Although you can catch any exception using the following syntax

try:
    # code
    pass
except Exception as e:
    # code
    pass
Enter fullscreen mode Exit fullscreen mode

This is like a wild-card, i.e it can catch any exception. It is good for some cases, but assume you are building a UI or an API of some sort and want to give a more descriptive message to the user. You can handle specific exceptions as well. We will discuss a few of the common built-in exceptions below. We will discuss what they mean, look at examples that raise them and handle them using a try...except clause. Some of them are pretty self-explanatory but we will still go over them

ZeroDivisionError

Cause

This error is raised when we try to divide a number by 0.

print(10/0)
Enter fullscreen mode Exit fullscreen mode

Error Message

ZeroDivisionError: division by zero
Enter fullscreen mode Exit fullscreen mode

Handling the Error

try:
    print(10/0)
except ZeroDivisionError:
    print("Tried to divide a number by 0")
Enter fullscreen mode Exit fullscreen mode

ImportError

Cause

This error is raised when we try to import a library or module which has not been installed or doesn't exist

import randomLibrary
from random import randomLibrary
Enter fullscreen mode Exit fullscreen mode

Error Message

The first statement would cause the following error

ModuleNotFoundError: No module named 'randomLibrary'
Enter fullscreen mode Exit fullscreen mode

The second statement would cause the following error

ImportError: cannot import name 'randomLibrary' from 'random'
Enter fullscreen mode Exit fullscreen mode

Handling the Error

Both can be caught in the same way

try:
    from random import randomLibrary
except ImportError:
    print("Could not find Library/Module")

try:
    import randomLibrary
except ImportError:
    print("Could not find Library/Module")
Enter fullscreen mode Exit fullscreen mode

FileNotFoundError

Cause

This error is raised when trying to open a file that doesn't exist

with open("nonExistingFile.txt") as f:
    print(f)
Enter fullscreen mode Exit fullscreen mode

Error Message

FileNotFoundError: [Errno 2] No such file or directory: 'nonExistingFile.txt'
Enter fullscreen mode Exit fullscreen mode

Handling the Error

try:
    with open("nonExistingFile.txt") as f:
        print(f)
except FileNotFoundError:
    print("Could not find the file")
Enter fullscreen mode Exit fullscreen mode

Type Error

Cause

This error is raised when you use a built-in function on the wrong data type

var1 = 10
var2 = "string"
print(var1 + var2)
Enter fullscreen mode Exit fullscreen mode

We are trying to add a string and an integer which raises a TypeError

Error Message

TypeError: unsupported operand type(s) for +: 'int' and 'str'
Enter fullscreen mode Exit fullscreen mode

Handling the Error

try:
    var1 = 10
    var2 = "string"
    print(var1 + var2)
except TypeError:
    print("You tried an operation on different datatypes")
Enter fullscreen mode Exit fullscreen mode

Assertion Error

Cause

This Error is raised by an assert statement in your code.

assert 10 == 0
Enter fullscreen mode Exit fullscreen mode

When the expression is False, the error is raised

Error Message

AssertionError
Enter fullscreen mode Exit fullscreen mode

Yup, that's it

Handling the Error

try:
    assert 10 == 0
except:
    print("Assertion Error Raised")
Enter fullscreen mode Exit fullscreen mode

Attribute Error

Cause

This error is raised when a non-existent attribute of a class is referenced

class test:
    def __init__():
        print("Initialized")

print(test.func())
Enter fullscreen mode Exit fullscreen mode

Error Message

AttributeError: type object 'test' has no attribute 'func'
Enter fullscreen mode Exit fullscreen mode

Handling the Error

class test:
    def __init__():
        print("Initialized")

try:
    print(test.func())
except AttributeError:
    print("Attribute doesn't exist")
Enter fullscreen mode Exit fullscreen mode

IndexError

Cause

This error is caused when you try to index a list with an index that doesn't exist or is out of range

lst = [1,2,3,4]
print(lst[5])
Enter fullscreen mode Exit fullscreen mode

Error Message

IndexError: list index out of range
Enter fullscreen mode Exit fullscreen mode

Handling the Error

try:
    lst = [1,2,3,4]
    print(lst[5])
except:
    print("Index is out of range")
Enter fullscreen mode Exit fullscreen mode

KeyError

Cause

This is similar to the Index Error but is caused when a reference is made to a non-existent key of a dictionary

dictionary = {'key1': "value1"}
print(dictionary["key2"])
Enter fullscreen mode Exit fullscreen mode

Error Message

KeyError: 'key2'
Enter fullscreen mode Exit fullscreen mode

Handling the Error

try:
    dictionary = {'key1': "value1"}
    print(dictionary["key2"])
except:
    print("Key doesn't exist in dictionary")
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rahulbanerjee99
Rahul Banerjee

Posted on April 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

#Day14 - Exceptions in Python
100daysofcode #Day14 - Exceptions in Python

April 4, 2021