#Day14 - Exceptions in Python
Tags: 100daysofcode, python, codenewbie, programming
Published: 2021-04-04 00:09:22

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

Although you can catch any exception using the following syntax
```python
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.
```python
print(10/0)
```

#### Error Message
```python
ZeroDivisionError: division by zero
```

#### Handling the Error
```python
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
```python
import randomLibrary
from random import randomLibrary
```

#### Error Message
The first statement would cause the following error
```python
ModuleNotFoundError: No module named 'randomLibrary'
```
The second statement would cause the following error
```python
ImportError: cannot import name 'randomLibrary' from 'random'
```

#### Handling the Error
Both can be caught in the same way
```python
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
```python
with open("nonExistingFile.txt") as f:
    print(f)
```
#### Error Message
```python
FileNotFoundError: [Errno 2] No such file or directory: 'nonExistingFile.txt'
```
#### Handling the Error
```python
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
```python
var1 = 10
var2 = "string"
print(var1 + var2)
```
We are trying to add a string and an integer which raises a TypeError

#### Error Message
```python
TypeError: unsupported operand type(s) for +: 'int' and 'str'
```
#### Handling the Error
```python
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.
```python
assert 10 == 0
```
When the expression is False, the error is raised
#### Error Message
```python
AssertionError
```
Yup, that's it

#### Handling the Error
```python
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
```python
class test:
    def __init__():
        print("Initialized")

print(test.func())
```
#### Error Message
```python
AttributeError: type object 'test' has no attribute 'func'
```
#### Handling the Error
```python
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
```python
lst = [1,2,3,4]
print(lst[5])
```
#### Error Message
```python
IndexError: list index out of range
```

#### Handling the Error
```python
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
```python
dictionary = {'key1': "value1"}
print(dictionary["key2"])
```
#### Error Message
```python
KeyError: 'key2'
```

#### Handling the Error
```python
try:
    dictionary = {'key1': "value1"}
    print(dictionary["key2"])
except:
    print("Key doesn't exist in dictionary")
```