SoFunction
Updated on 2025-04-26

Detailed explanation of try except statement and practical application in Python

Preface

In Python,tryandexceptYes forException handlingKeywords, they can catch errors (i.e. exceptions) that may occur during the run, thereby avoiding program crashes or unexpected behavior.

usetry-exceptStatements allow programs to handle errors gracefully instead of throwing errors directly and interrupting execution.

Basic syntax of try-except

try:
    # The block of code attempted to execute    # Code that may throw exceptionsexcept ExceptionType:
    # The block of code executed when a specified exception occurs    # Logic for handling exceptions

1. try statement

tryStatements are used to wrap blocks of code that may throw exceptions. Python will try to executetryAll statements in the block.

iftryThe code in the block executes normally without errors, and it will be skippedexceptBlock, continue to execute the following code.

2. Except statement

exceptThe statement defines whentryHow should the code in the block handle the exception when it throws an exception?

exceptYou can specify the captured exception type later, such asZeroDivisionErrorValueErroretc. or use generalExceptionto catch all types of exceptions.

Catch a specific type of exception

try:
    result = 10 / 0  # will raise ZeroDivisionErrorexcept ZeroDivisionError:
    print("Divid by zero error")

Catch all exceptions

try:
    # Possible error code    result = 10 / 0
except Exception as e:  # Catch all exceptions and assign them to e    print(f"An error occurred: {e}")

In the above example,Exception as eCatch all exceptions and store them inein variable. Then, we can output specific information about the exception.

3.else and finally

Apart fromtryandexceptPython's exception handling mechanism also provideselseandfinallyStatements, these statements can be used to deal with different situations.

  • elseStatement: IftryThe code in the block does not throw an exception, and it will be executedelseCode in the block.elseStatements are usually used to execute code that should only be executed if there is no exception.

  • finallyStatement: Regardless of whether an exception occurs or not,finallyThe code in the block will always be executed. Usually used to perform cleanup operations, such as closing files or freeing resources.

Example

try:
    result = 10 / 2  # No errorexcept ZeroDivisionError:
    print("Divid by zero error")
else:
    print("No exception occurred, calculation result:", result)
finally:
    print("This is the final execution part, whether an error occurs or not")

Output:

No exception occurred, calculation result: 5.0
This is the final execution, whether an error occurs or not

No exception occurred, calculation result: 5.0 This is the final execution part, whether an error occurred or not

4. Catch multiple exceptions

onetryBlocks can contain multipleexceptBlocks are used to catch different types of exceptions respectively. When multiple exceptions may occur, different handling methods can be provided according to different exception types.

try:
    num = int(input("Please enter a number: "))
    result = 10 / num
except ValueError:
    print("Please enter a valid number")
except ZeroDivisionError:
    print("Divid by zero error")

In this example, the program will judge that the user input isValueErrorstillZeroDivisionError, and then give the corresponding error message.

5. Practical application scenarios of try-except

try-exceptStatements are very useful in many practical applications, especially in the following scenarios:

  • File Operation: When opening a file, the file may not exist or have no permission to read.
  • Network request: The network connection may fail or the request timeout.
  • User input: The content entered by the user may not be converted to the desired type (such as a number).
  • Function calls to external libraries: Unforeseen exceptions may be encountered when calling external libraries.

Example: File Operation

try:
    with open("", "r") as f:
        content = ()
except FileNotFoundError:
    print("The file is not found, please check the path")
except PermissionError:
    print("Permission error, please check the permissions of the file")

6. Else and finally in try-except

In some cases, we want to execute some code when there is no exception and some code when the resource is finally cleaned.

Example: Database Operation

try:
    # Suppose you connect to the database and execute the query    connection = open_database_connection()
    result = query_database(connection)
except DatabaseError as e:
    print(f"Database error: {e}")
else:
    print("Query successful")
finally:
    ()  # Whether there is an exception or not, the database connection needs to be closed

7. Summary of the usage of else and finally in try-except

  • tryExecute code that may have errors
  • except: Catch and handle exceptions
  • else: ifNo exception occurred,implementelseCode in
  • finally: Code that will be executed regardless of whether an exception occurs (usually used for cleaning work)

8. Summary

try-exceptIt is a very powerful exception handling mechanism in Python, which can help programs handle errors elegantly.

By catching specific exception types, we can control how errors are handled so that the program does not crash directly when facing unexpected situations. Combinedelseandfinally, we can ensure the correctness of the code and the cleanup of resources.

In actual development, use it reasonablytry-exceptStatements can improve the robustness of the code, avoid the program being terminated by a small error, and thus improve the user experience.

This is the end of this article about try except statements and practical applications in Python. For more detailed explanations of Python try except, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!