Rahul Banerjee

#Day14 - Exceptions in Python

#Day14 - Exceptions in Python

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

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

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)

Error Message

ZeroDivisionError: division by zero

Handling the Error

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

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

Error Message

The first statement would cause the following error

ModuleNotFoundError: No module named 'randomLibrary'

The second statement would cause the following error

ImportError: cannot import name 'randomLibrary' from 'random'

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

FileNotFoundError

Cause

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

with open("nonExistingFile.txt") as f:
    print(f)

Error Message

FileNotFoundError: [Errno 2] No such file or directory: 'nonExistingFile.txt'

Handling the Error

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

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)

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'

Handling the Error

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

Assertion Error

Cause

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

assert 10 == 0

When the expression is False, the error is raised

Error Message

AssertionError

Yup, that's it

Handling the Error

try:
    assert 10 == 0
except:
    print("Assertion Error Raised")

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

Error Message

AttributeError: type object 'test' has no attribute 'func'

Handling the Error

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

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

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

Error Message

IndexError: list index out of range

Handling the Error

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

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

Error Message

KeyError: 'key2'

Handling the Error

try:
    dictionary = {'key1': "value1"}
    print(dictionary["key2"])
except:
    print("Key doesn't exist in dictionary")
#100daysofcode#codenewbies#python#programming-blogs#python3
 
Share this