Kodeclik Logo

Learn More

Fall 2025

Kodeclik Blog

Python's try-except mechanism is a powerful tool for handling errors and exceptions in your code.

For instance, consider the below code:

The output will be:

As can be seen, the first line produces a proper result, i.e., 1. But the second line led to an error, called an “exception”. We get the message that we have reached a “ZeroDivisionError”. Most importantly, the program is aborted and the third print statement is not reached at all.

Modifying a Python function to use a try-except block

Python’s try-except block is a way to gracefully handle such potential errors and not cause programs to abort unceremoniously. Here’s how that would work:

The output is:

Note that we have replaced the “5/5”, “5/0” etc with safe_divide(5, 5) and safe_divide(5, 0), etc.

This function, safe_divide, takes two parameters, x and y, and attempts to divide x by y. It uses a try-except-else block for error handling. Firs, the try block attempts the division operation. If a ZeroDivisionError occurs (when y is zero), it's caught by the except block, which prints an error message. If no exception occurs, the else block executes, printing the result of the division.

Template for setting up a Python try-except block

In general, here is a simple template of how to setup a try-except block and when to use it:

Python try except block

Handling other types of errors in Python

Note that our earlier code works only if the exception is a “ZeroDivisionError”. If you tried using the code like so:

you will get:

To trap errors of this kind, you will need to expand your try-except block like:

Now the output will be:

as expected.

There are many other examples of where you will need to use Python try-except blocks. Below are a few of them.

Python try-except block for file handling

Below is an example that shows how to safely open and read a file, handling potential errors:

This function handles specific file-related exceptions and provides appropriate error messages. It uses a try-except block to catch potential errors such as FileNotFoundError, PermissionError, and IOError, providing specific error messages for each case. This function ensures that common file-related issues are handled gracefully, preventing the program from crashing and giving users clear feedback about what went wrong during the file reading process.

Python try-except block for JSON parsing

Below is an example demonstrating error handling when parsing JSON data:

This example showcases error handling when working with JSON data in Python. It utilizes the json module to parse a JSON string and handles two main types of errors: JSONDecodeError for invalid JSON format and TypeError for non-string inputs. By catching these specific exceptions, the function can provide meaningful error messages to users, making it easier to identify and correct issues with JSON data input, which is crucial in many data processing and API-related tasks.

Python try-except block for connecting to databases

This example shows how to handle errors when connecting to a database (using a hypothetical database library):

This example illustrates error handling in the context of connecting to a database using a hypothetical database library. It demonstrates how to catch and handle various database-related exceptions such as ConnectionError, AuthenticationError, and general DatabaseError. This approach allows the function to provide specific feedback for different types of connection issues, such as network problems or invalid credentials, enhancing the user experience and making database interactions more reliable and informative in applications that require database access.

In summary, try-except blocks can be used to handle different types of errors in various scenarios, making your code more robust and user-friendly. They show the importance of catching specific exceptions before general ones and providing informative error messages to users or logging systems.

Want to learn Python with us? Sign up for 1:1 or small group classes.

Kodeclik sidebar newsletter

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

About

Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.

Copyright @ Kodeclik 2025. All rights reserved.