Error Handling in Python Part 8

Error Handling in Python Part 8

Samer Mahamid's photo
Samer Mahamid
·May 30, 2022·

5 min read

Introduction

Errors are never fun to deal with, but Python makes it easy for you to handle them. In this post, we'll talk about what errors are: think of errors as bugs that pop up in your code when something goes wrong. Then, we'll explain the various types of errors that Python can generate and how to handle them.

Exception Handling

In Python, exceptions are a way of handling errors in a program.

Exceptions can occur when the execution of a program goes wrong or encounters an unexpected condition (for example: divide by zero).

When you encounter an error in your code, Python will raise an exception. It’s up to the developer to catch it and handle it properly by wrapping the code in try-except blocks.

There are two types of exceptions:

In Python, exceptions are divided into two categories:

SyntaxError. These are raised when the source code you wrote is invalid.

IndexError. Raised when an index is out of bounds or beyond the length of the sequence.

As you can see from the types above, there are many more different kinds of exceptions than just those two categories!

Syntax errors, also known as parsing errors, are perhaps the most common complaint you get while still learning python.

while True print('hello world')
               ^
# SyntaxError: invalid syntax

Exception Even if a statement or expression is syntactically correct it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions. When an exception is not handled it results in an error mass.

Example:

>>>10*(1/0)
error: ZeroDivisionError: division by zero
>>> 4 + spam * 3
error:NameError: name 'spam' is not defined
>>>'2' + 2 
error: TypeError:Can't convert 'int' object to srt implicitly

Common Errors Types

  • SyntaxError
  • IndexError is thrown when trying to access an item at an invalid index
  • KeyError is thrown when a key is not found
  • TypeError is thrown when an operation or function is applied to an object of an inappropriate type like: TypeError: must be 'str', not 'int'

  • ValueError is thrown when a functions argument is of an inappropriate like: ValueError: invalid literal for int() with base10: 'xyz'

  • NameError is thrown when an object could not be found like: NameError: name 'age' is not defined.

Catching Exceptions

It is possible to write programs that handle selected exceptions

while True:
     try:
         x = int(input('Please enter a number'))
     except ValueError:
         print('Oops! That was no valid number. Try again')

We handle only value so if another error occurs the error message will show up anyway

Try statement

The try statement works as follows:

  • The try clause is executed
  • If no exceptions occur the except clause is skipped
  • If the type of the exception matches the except clause is executed
  • If the exception is unhandled and execution stops with a message

Except statement

An except clause may name multiple exceptions as a parenthesized tuple

except(RuntimeError, TypeError, NameError)

Finally statement

If a finally clause is present the final clause will execute as the last task before the try statement completes. The finally clause runs whether or not the try statement produces an exception.

try:
    x = int('Anna')
except ValueError:
    print('Cannot convert str to int')
finally:
    print('finally block')

In most cases, we want to be as specific as possible. We can call multiple except like:

try:
    pass
except ValueError:
    pass
except TypeError:
    pass

Raising Exceptions

Python raise Keyword is used to raise exceptions or errors. The raise keyword raises an error and stops the control flow of the program. It is used to bring up the current exception in an exception handler so that it can be handled further up the call stack.


input = 5

if input != str:
    raise Exception("The input should be a string")

#    raise Exception("The input should be a string")
# Exception: The input should be a string

We can use the try statement with raise

name = 'Anna'

try:
    number = int(name)
except ValueError:
    raise ValueError("String can't be changed into integer")

# raise ValueError("String can't be changed into integer")
# ValueError: String can't be changed into integer

Custom Exception

Python will handle any errors generated by other functions in your code. This means that you don't have to worry about handling the errors, as Python does it for you. However, there are some exceptions to this rule. If a programmer wants to handle an error themselves, they can do so by raising an exception or creating a custom exception class of their own.

Example custom exception class:

class Error(Exception):
    """Base class for other exceptions"""
    pass


class LenStringTooSmall(Error):
    """ Will raise if the length of the string is less than 4 """


def verify_len(string):
    if len(string) < 4:
        raise LenStringTooSmall
    else:
        print('Len of the string is: ' + str(len(string)))


verify_len('Sss')

#    raise LenStringTooSmall
# __main__.LenStringTooSmall

Conclusion

This is an important topic to learn in the beginning stages of learning Python. One of the main things for us to understand about Python exceptions is that we will encounter them. We should be prepared for them and handle them properly. When it comes to writing Python applications, it's always a good idea to use Try-Except blocks. It's also helpful to know where to look if you do encounter such exceptions.

 
Share this