Handling exceptions in Python

This post is lesson 31 of 54 in the subject Python Programming Language

1. Handling exceptions in Python with try statement

When an exception occurs in Python, the program will stop suddenly and display an error message. To avoid this, we need to handle exceptions, so we can identify errors and fix them later. Python provides us with the try and except statements for handling exceptions.

The try statement checks for exceptions in the code within the try block. If there is an exception, it will be passed to the except block for handling. For instance, an exception happens when we divide a number by 0.

try:
    x = 1/0
    print(x)
except:
    print("An exception occurred!")

Result

An exception occurred!

Python allows us to catch many specific exceptions thrown from the try block.

try:
    x = 1/0
    print(x)
except TypeError:
    print("Data type of variable is not suitable type!")
except ZeroDivisionError:
    print("Cannot divide by 0!")
except:
    print("An exception occurred!")

Result

Cannot divide by 0!

2. Using try statement with else statement

We can use the else keyword to define a block of code that will be executed if no exceptions occur.

try:
    x = 1/1
    print(x)
except ZeroDivisionError:
    print("Cannot divide by 0!")
else:
    print("Nothing wrong.")

Result

1.0
Nothing wrong.

The code block in the else statement won’t run if an exception occurs.

try:
    x = 1/0
    print(x)
except ZeroDivisionError:
    print("Cannot divide by 0!")
else:
    print("Nothing wrong.")

Result

Cannot divide by 0!

3. Using try statement with finally statement

In Python, we can use the try statement together with the finally statement. The finally block will always be executed, regardless of whether the try block raises an exception or not.

try:
    x = 1/0
    print(x)
except ZeroDivisionError:
    print("Cannot divide by 0!")
finally:
    print("The 'try except' is finished!")

Result

Cannot divide by 0!
The 'try except' is finished!

We commonly use the finally block to close streams while reading/writing files or to close connections to the database.

# The try block will raise an error when trying to write to a read-only file
try:
    file = open("gochocit.txt")
    try:
        file.write("Welcome to gochocit.com!")
    except:
        print("Something went wrong when writing to the file!")
    finally:
        # always close file
        file.close()
except:
    print("Something went wrong when opening the file!")

Result

Something went wrong when writing to the file!

4. Handling exceptions in Python with raise keyword

In Python, you can use the raise keyword to trigger an exception when a certain condition is met.

a = 1
b = 0

if b == 0:
  raise Exception("Sorry, cannot divide by 0!")
else:
    print("x = ", a/b)

Result

Traceback (most recent call last):
  File "c:\python-examples\example.py", line 5, in <module>
    raise Exception("Sorry, cannot divide by 0!")
Exception: Sorry, cannot divide by 0!

We can use the raise keyword to throw a specific exception.

a = 1
b = 0

if b == 0:
  raise ZeroDivisionError("Sorry, cannot divide by 0!")
else:
    print("x = ", a/b)

Result

Traceback (most recent call last):
  File "c:\\\\python-examples\\\\example.py", line 5, in <module>
    raise ZeroDivisionError("Sorry, cannot divide by 0!")
ZeroDivisionError: Sorry, cannot divide by 0!
5/5 - (1 vote)
Previous and next lesson in subject<< Errors and Exceptions in PythonBuilding class and creating object in Python >>

Leave a Reply

Your email address will not be published. Required fields are marked *