Python Exception Handling: A Comprehensive guide on Try, Except, Try catch, Finally 2025

0
31
Exception handling

In python or any other programming language, you might face to the situation when you have to write the code that is risky and can generate an error or may crash the program. You are in the doubt that the code you are going to write may have some logical or runtime errors. So, in this scenario python gives you Try Except blocks to handle this situation. In case if there is an error in the try block python will skip the try block and executes the except block. This is the very similar situation like if else statement where an if statement can not be executed then the else block will execute.

Errors and Exception Handling In Python

In python or any other programming language, errors are the basic part of development process. To avoid the errors python provides the tools to detect, report and handle the errors gracefully.

There are basically two types of errors in python that may occur or crash the program. These are:

  1. Syntax errors.
  2. Exceptions.

What are Syntax Errors In Python?

Syntax are the most common type of errors also called parsing errors. The syntax error may occur when the code or program violates the language’s grammar such as missing punctuation like colon, or incorrect code structure etc.

For example:

while True print('Hello world')

When I run this code, it shows:

It shows the error Invalid syntax. The correct version of the code is:

while True:
        print('Hello world')

What Are Exceptions in python?

Exception are the errors that may error during the program execution. Exception can also occur if the program is syntactically correct. But, you need not to worry about Exception handling in python because I will explain Exception handling in detail. Let us first explore some exception errors for better understanding.

10 / 0          #zeroDivisionError4 + spam * 3       #nameError(spam not defined)
'2' + 2         #TypeError(can't add string and integer) 

As you can see exceptions can occur in different ways. The last line of error message indicates the type of exception. some common types of exceptions are:

  • ZeroDivisionError – when you try to divide by zero.
  • NameError – when you use a variable that doesn’t exist.
  • TypeError – when you use the wrong kind of value.

The error name shown (like TypeError) tells you what kind of built-in error it is. This name is a regular word in Python, but not a special keyword.

After the error type, Python also gives more detail to help you explain what caused the error.

Before the last line, Python shows where the error happened in your code. This is called a traceback, and it helps you to find the exact line that caused the problem.

Some common Exception errors are:

1. IOError

Occurs when the program is trying to open a file that doesn’t exist.

Example:

try:
    f = open("nonexistent_file.txt")
except IOError:
    print("File cannot be opened.")

2. KeyboardInterrupt

Occurs when the user try to stop a running program manually (like pressing Ctrl+C).

Example:

try:
    while True:
        pass  # Infinite loop
except KeyboardInterrupt:
    print("Program interrupted by user.")

3. ValueError

This type of error can occur when the data type of function is correct but the input is wrong.

Example:

try:
    number = int("abc")
except ValueError:
    print("Cannot convert to integer.")

4. EOFError

Occurs when user input is expected , but there’s no data to read.

Example:

try:
    data = input("Enter something: ")
except EOFError:
    print("No input was provided.")

5. ImportError

Happens when the Python interpreter can not find or load a module you are trying to import.

Example:

try:
    import non_existing_module
except ImportError:
    print("Module not found.")

You have understand what are exception errors actually. Now, lets explore how to avoid exceptions in python.

Exception Handling In Python

To prevent you program from unexpected crash due to unexpected errors, python provides exception handling using Try Except block.

What does Try do in python?

In python Try is used to handle exception errors to prevent the program from crashing. The try works as:

  • You try to run some code.
  • If there is an error, Python catches it and runs another block of code instead of stopping the program.

How to use try and except in python?

Try and except(also known as try catch) pair is used to handle exception handling in python. Just like if-else, the try block will executes only if there are no errors in the try block, if the try block have error then the except block will executes.

Syntax of Try Except block

try:
    # Code
except:
    # Executed if error in the
    # try block

How try works in python?

  • Python runs the code inside the try block.
  • If there’s no error in the try block, the except block will be skipped.
  • If there is an error in the try block, Python skips the rest of the try block and runs the matching except block.
  • If no matching except block is found, the error is passed to any outer try blocks. If no code to handle it, the program crashes.
  • You can have multiple except blocks to handle different types of errors.

Exception Handling through Different use cases

Execution of try block

def convert_to_int(value):
    try:
        number = int(value)
        print("Conversion successful! The number is:", number)
    except ValueError:
        print("Oops! That was not a valid number.")

# Call the function with a value that will NOT cause an error
convert_to_int("43")

Lets run this code and see the results.

So, in the above example you can clearly see that the try is executed and except block is skipped.

Execution of Except block

In the above example of there is non integer input then the except block will be executed.

def convert_to_int(value):
    try:
        number = int(value)
        print("Conversion successful! The number is:", number)
    except ValueError:
        print("Oops! That was not a valid number.")

# Call the function with a value that will NOT cause an error
convert_to_int("FARYAL")

Lets run this code and see the output.

Multiple Except Blocks

A try block may have different except blocks to handle multiple exceptions at the same time. This approach makes debugging easier.

In this example we are going to read a number from the list and divide it. Lets write the code.

def process_list(data, index):
    try:
        number = data[index]          # May raise IndexError
        result = 100 / int(number)    # May raise ValueError or ZeroDivisionError
        print("Result is:", result)
    except IndexError:
        print("Error: The index you gave is out of range.")
    except ValueError:
        print("Error: The item at the index is not a valid number.")
    except ZeroDivisionError:
        print("Error: You tried to divide by zero.")

Lets run this code and see the output.

So, you can, it is possible to handle multiple except blocks at the same time.

No Exception -The Else clause

The else clause is used with the combination of try except to run the try block if no exception occurs. Lets figure it out with example.

try:
     number = int(input("Enter a number: "))
except ValueError:
     print("Invalid number.")
else:
     print("You entered:", number)

In this example, if the user enter an integer than the else block will be executed. and if the user enter non integer number than the except block will be executed. Lets run this code and see the results.

You can try with non integer number and see the output.

The Finally clause For Exception Handling

The primary purpose of finally clause is to close the clean up the resources. This clause will always be executed no matter there is an exception or not. Lets understand this by example.

try:
    file = open("myfile.txt")
# Process file
finally:
    file.close()

Raising Exceptions Manually

Normally, Python raises exceptions automatically when something goes wrong (like dividing by zero).

But sometimes, you might want to raise an error on purpose to:

  • stop the program when something is wrong,
  • make your code safer,
  • give a clear error message.

You do this using the raise keyword. Let us understand this by example.

def check_age(age):
    if age < 0:
        raise ValueError("Age cannot be negative!")
    print("Age is valid:", age)

check_age(-5)

Lets run this code and see the output.

So, we can raise the exception when there is a need to avoid the problem that might be occured.

Exception Chaining

Exception chaining happens when one exception causes another exception.

Python helps you link (or “chain”) those two exceptions together, so you can understand what originally went wrong.

This is useful for debugging — it shows both the original problem and the new one that happened because of it. lets understand by example.

try:
    num = int("hello")  # This will raise ValueError
except ValueError as e:
    raise RuntimeError("Failed to convert string to int") from e

Now, lets run this code.

Creating Custom Exceptions

In python, you can create your own custom exception that might be specific to your program. For example:

class MyError(Exception):
    pass

def check_number(num):
    if num < 0:
        raise MyError("Number must be positive!")

check_number(-5)

Now, lets run this code to see the output

Adding Notes to Exceptions

In Python 3.11 and later, you can add extra information (called a “note”) to an exception using the .add_note() method.
This helps to make the error message more clear and helpful when something goes wrong.

def process_age(age):
    try:
        if not isinstance(age, int):
            raise TypeError("Age must be an integer")
        if age < 0:
            raise ValueError("Age cannot be negative")
        print("Age {age} is valid.")
    except Exception as e:
        e.add_note("Error occurred while checking user age.")
        raise

# Test the function
process_age("twenty")   # Triggers TypeError

  • The function expects an integer.
  • "twenty" is a string, so it raises a TypeError.
  • Before raising it, we add a note: "Error occurred while checking user age."
  • When the error shows, the note gives helpful context.

now lets run this and see the output.

Conclusion

Python error and exception handling system is powerful, flexible, and essential for building reliable applications. By understanding how errors work and how to handle them correctly, you can write code that is robust, user-friendly, and easier to debug.

For any query and suggestions about exception handling please leave a comment or contact us.

LEAVE A REPLY

Please enter your comment!
Please enter your name here