Preface
In Python,try
andexcept
Yes forException handlingKeywords, they can catch errors (i.e. exceptions) that may occur during the run, thereby avoiding program crashes or unexpected behavior.
usetry-except
Statements 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
try
Statements are used to wrap blocks of code that may throw exceptions. Python will try to executetry
All statements in the block.
iftry
The code in the block executes normally without errors, and it will be skippedexcept
Block, continue to execute the following code.
2. Except statement
except
The statement defines whentry
How should the code in the block handle the exception when it throws an exception?
except
You can specify the captured exception type later, such asZeroDivisionError
、ValueError
etc. or use generalException
to 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 e
Catch all exceptions and store them ine
in variable. Then, we can output specific information about the exception.
3.else and finally
Apart fromtry
andexcept
Python's exception handling mechanism also provideselse
andfinally
Statements, these statements can be used to deal with different situations.
else
Statement: Iftry
The code in the block does not throw an exception, and it will be executedelse
Code in the block.else
Statements are usually used to execute code that should only be executed if there is no exception.finally
Statement: Regardless of whether an exception occurs or not,finally
The 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
onetry
Blocks can contain multipleexcept
Blocks 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 isValueError
stillZeroDivisionError
, and then give the corresponding error message.
5. Practical application scenarios of try-except
try-except
Statements 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
-
try
: Execute code that may have errors -
except
: Catch and handle exceptions -
else
: ifNo exception occurred,implementelse
Code in -
finally
: Code that will be executed regardless of whether an exception occurs (usually used for cleaning work)
8. Summary
try-except
It 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. Combinedelse
andfinally
, we can ensure the correctness of the code and the cleanup of resources.
In actual development, use it reasonablytry-except
Statements 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!