Python Exception Handling With Examples

This article entitled Python Exception Handling is a continuation of the previous article entitled Python Function.

In Python, exception handling is an event that occurs in the execution of the program that can cause disruption of the normal flow of the program execution.

For instance that a program will encounter this kind of situation that will not cope with it and will raise an exception. This exception is an object that will represent an error.

try…except block in Python

A Python try…except block is used for handling exceptions.

Syntax

try:
    # code that may cause exception
except:
    # code to run when an exception occurs

We put the code which might generate an exception within the (try block). Each (try block) is accompanied by the except block.

When the exceptions will occur, the except block will see or be caught and the except block will come on each attempt block.

Example

try:
    numerator = 30
    denominator = 0

    result = numerator/denominator

    print(result)
except:
    print("Error: Denominator cannot be 0.")

# Output: Error: Denominator cannot be 0. 

Output

Error: Denominator cannot be 0.

In the above example, the program divides a number by 0 and the code generates an (exception).

In order to handle this exception, we put a code (result = numerator/denominator) within the try block, In case the exception happens the rest of the code within the (try block) will be skipped.

An except block will catch the statements and an exception within the except block is executed.

Once there is none of the statements in the (try block) generates any exception, the (except block) is ignored.

Python Catching Specific Exceptions

Catching specific exceptions for every (try block), there will be a zero or multiple except blocks. The multiple (except) blocks will allow handling every exception in a different way.

This type of argument of every except block will indicate a type of exception that can be handled by it.

Example

try:
    
    even_numbers = [10,40,60,80]
    print(even_numbers[7])

except ZeroDivisionError:
    print("Denominator cannot be 0.")
    
except IndexError:
    print("Index Out of Bound.")

# Output: Index Out of Bound

Output

Index Out of Bound.

In the above example, we have been creating the list of even_number.

The list of an index which always starts from 0 and the last element of the list index is 3.

Look at the statement

print(even_numbers[5])

An IndexError exception occurs for the reason of we are trying to access the value in index 5.

  • A ZeroDivisionError exception will be ignored
  • The code that was set within the IndexError exception is executed.

try with else clause in Python

In some instances, we might run the certain (block of code) once the (block of code) within the try and run without errors

In that case, Python allows us to use an optional (else keyword) together with a try statement.

Example

try:
    number = int(input("Enter a number: "))
    assert number % 3 == 0
except:
    print("Not an even number!")
else:
    reciprocal = 1/number
    print(reciprocal)

Output

Enter a number: 5
Not an even number!

try..finally in Python

finally block in Python is always (executed) no matter if there is an exception or none and the finally block is optional and for every try block there is a single finally block.

Example

try:
    numerator = 20
    denominator = 0

    results = numerator/denominator

    print(results)
except:
    print("Error: Denominator cannot be 0.")
    
finally:
    print("This is finally block.")

Output

Error: Denominator cannot be 0.
This is finally block.

The above example is that we divide the number by 0 within the try block and the code will generate an exceptions

This exception is caught by an except block and the finally block will be executed.

Summary

In summary, you have read about Python Exception Handling. We also discussed in this article the try…except block, catching specific exceptions, try with else clause, and try..finally.

I hope this article could help you a lot to continue pursuing learning this powerful programming language.

If you want to learn more check out my previous and latest articles for more career-changing articles.

Leave a Comment