You are currently viewing Python Try Except with Examples

Try Except in Python is essential for handling and managing errors that may occur during program execution. The try-except block is one of the most commonly used features in Python programming. In this article, we will take a closer look at the Python Try Except block, including its syntax and how to use it in different scenarios.

Advertisements

1. Quick Examples of Try Except

These quick examples of try-except in Python demonstrate some of the basic ways to handle errors and exceptions in your code. There are many more advanced use cases for Python Try Except that we will see.


# Example 1: Catching a specific exception
try:
    x = 1 / 0  # division by zero will raise a ZeroDivisionError
except ZeroDivisionError:
    print("Oops! You cannot divide by zero.")

# Example 2: Handling multiple exceptions
try:
    file = open("myfile.txt")  # open a file
    line = file.readline()  # read the first line
    x = int(line)  # convert the line to an integer
except (IOError, ValueError) as e:
    # catch both IOError and ValueError
    print("An error occurred: ", e)
finally:
    # ensure that the file is closed,
    file.close()

# Example 3: Raising an exception
try:
    age = int(input("Enter your age: "))
    if age < 0:
        # raise a ValueError with a custom error message
        raise ValueError("Age cannot be negative.")
except ValueError as e:
    # catch the raised ValueError and print the error message
    print("An error occurred: ", e)

2. Why we use Try Except in Python?

In Python, errors and exceptions can occur at runtime due to a variety of reasons, such as invalid input, network errors, file system errors, and so on. When such errors occur, they can cause the program to crash or behave unpredictably, which is not desirable. This is where Try Except comes in.

Try-except is a construct in Python that allows you to catch and handle exceptions that occur during the execution of your program. By wrapping potentially error-prone code in a try block, you can catch and handle any exceptions that occur in a graceful and controlled manner, instead of allowing them to propagate and cause your program to crash.

  • Error handling: catch and handle exceptions in a controlled way, preventing your program from crashing and providing a more user-friendly experience for your users
  • Robustness: make your programs more resilient to errors by handling exceptions gracefully
  • Debugging: provide more detailed and helpful error messages that aid in debugging and troubleshooting
  • Testing: intentionally trigger exceptions in your code to test and ensure that it behaves as expected under different error conditions

3. What is Exception Handling

In Python, exceptions are raised when an error or exceptional condition occurs during the execution of a program. For example, trying to divide a number by zero will raise a ZeroDivisionError. If you don’t handle this error, your program will crash and provide an error message to the user.

Here come the Power of Exception Handling. Exception handling is a Process in programming that allows you to handle errors or exceptional conditions that may occur during the execution of a program. It is a way to recover from errors, prevent the program from crashing, and provide a more user-friendly experience.

Consider the following code that attempts to divide two numbers without exception handling:


x = 1
y = 0
z = x / y  # This line raises error
print(z)

In this example, the program tries to divide 1 by 0, which is an illegal operation and will cause a ZeroDivisionError. See the following Output.

python try except

This is not a great user experience, and it may be difficult to debug the program without more detailed error information.


x = 1
y = 0

try:
    z = x / y
except ZeroDivisionError:
    print("Error: Division by zero")

The except block catches the error and prints a user-friendly error message. The output of this code will be:


# Output:
Error: Division by zero

4. Syntax of Try Except

The Simplest Syntax of the Try-Except is below:


# Syntax of handling single exception
try:
    # code that may raise an exception
except ExceptionType:
    # code to handle the exception

You can also use multiple except blocks to handle different types of exceptions. Syntax for Handling Multiple Exception


# Syntax of handling multiple exceptions
try:
    # some code that may raise an exception
except ValueError:
    # code to handle a ValueError
except TypeError:
    # code to handle a TypeError
except:
    # code to handle any other exception

Syntax for a try-except block with finally and else clauses:


# Syntax with finally & else blocks
try:
    # some code that may raise an exception
except ExceptionType:
    # code to handle the exception
else:
    # code to run if no exception is raised
finally:
    # code to run regardless of whether an exception is raised or not

The table below explain keywords and clauses commonly used in try-except constructs:

KeywordDescription
tryThe keyword used to start a try block.
exceptThe keyword used to catch an exception.
elseAn optional clause that is executed if no exception is raised in the try block.
finallyAn optional clause that is always executed, regardless of whether an exception is raised or not.
raiseThe keyword used to manually raise an exception.
asA keyword used to assign the exception object to a variable for further analysis.
Python try-except Keywords

5. Try Except – Catching Specific Exceptions

Catching specific exceptions is an important part of exception handling in Python. We can use multiple except blocks to handle only the specific exceptions that are relevant to our code.

When we catch a specific exception, we can provide more precise and meaningful error messages to the user and take appropriate actions to handle the exception.

General Exception Handling:


try:
    with open(filename, 'r') as f:
        # perform some file operations
except:
    print("Error: file operation failed")

Specific Exception Handling:


try:
    with open(filename, 'r') as f:
        # perform some file operations
except FileNotFoundError:
    print("Error:not found")
except PermissionError:
    print(f"Error: Permission denied")

The reason why you should you do the Specific Exception Handling:

  • Specific exception handling provides better error handling with more informative error messages
  • Catching specific exceptions makes the code more readable and maintainable
  • Catching general exceptions can mask other errors, making it more difficult to diagnose and fix issues.

6. Finally Block in Try-Except

The finally block is often used to release resources like file objects or network connections that were opened in the try block, regardless of whether an exception was raised or not.

In finally block We put code that will always be executed, regardless of whether an exception was raised or not.


try:
    pass
except Exception as e:
    print(f"Error occurred: {e}")
finally:
    print("Finally Block")

7. Else Block in Try-Except

The else block in a try-except statement is an optional block of code that is executed if no exceptions are raised in the try block. This means that if no exceptions occur, the code in the else block is executed.

The else block is useful for performing actions that should only occur if no exceptions have been raised, such as printing a success message or updating a database.


try:
    result = x / y
except ZeroDivisionError:
    print("Error: Cannot divide by zero")
else:
    print(f"Result={result}")

8. Summary and Conclusion

We explaind basics of Python’s Try Except statements. We also explored the Finally and Else blocks. It is essential for creating robust and reliable code that can handle unexpected errors and provide more informative feedback to users. I hope this article has been helpful. If you have any question, please let me know in comment section.

Happy coding!