
错误处理是 Python 编程的一个关键方面,它允许开发人员编写健壮且有弹性的代码,这些代码可以优雅地处理意外情况或输入。
I. 了解 Python 中的异常Python 使用一种称为 exceptions 的机制来处理程序执行过程中可能出现的错误。发生错误时会引发异常,并且可以使用 try 块后跟 except 子句来捕获和处理异常。
II. 错误与异常错误:程序中停止执行的问题。(例如,SyntaxError)例外:可以处理的运行时问题(例如 ValueError、IndexError)。III. 异常处理中的关键概念1. 尝试区块包含可能引发异常的代码。执行直到发生异常。如果引发异常,则控制权将移至适当的 except 块。如果没有异常发生,else 块将在 try 块之后执行。2. 块除外捕获并处理 try 块中引发的异常。可以指定特定异常或对任何异常使用通用处理程序。如果 try 块成功执行(即没有异常),则改为执行 else 块。3. Else 块仅当 try 块完成且未引发任何异常时执行。对于如果成功,应在 try 块之后运行的代码很有用。4. 最后阻止无论是否引发异常,始终最后运行,因此非常适合清理操作。在 try 块之后运行,并在任何匹配的 except 或 else 块之后运行。5. Raise 语句用于根据特定条件在代码中手动引发异常。如果触发了 raise 语句,则控制权将移至相应的 except 块。如果引发异常,将跳过 else 块。
以下是使用内置函数时会遇到的一些常见异常:
TypeError:将操作或函数应用于不适当类型的对象时引发。ValueError:当函数收到类型正确的参数但值不适当时引发。IndexError:尝试访问列表中范围之外的索引时引发。KeyError:找不到字典键时引发。ZeroDivisionError:尝试除以零时引发。示例代码结构:try: # Potentially problematic operation except SomeException: # Handling exception else: # Executed if try is successful finally: # Cleanup code that always runs示例:使用内置函数进行错误处理让我们探索一些使用内置函数时错误处理的实际示例。
示例 1:使用try和except使用 try 测试代码是否存在错误,使用 except 处理异常。def convert_to_integer(user_input): try: number = int(user_input) print(f'Result of function: {number}') except ValueError: # Handle non-integer input print("Error: Invalid input! Please enter a valid integer.") # Example usage convert_to_integer(50.22)convert_to_integer("abc") # This will trigger the ValueError输出:
Result of function: 50Error: Invalid input! Please enter a valid integer.示例 2:使用Raise语句当出现特定条件时,故意引发异常。def divide_numbers(a, b): if b == 0: # Raise an exception if b is zero raise ValueError("Cannot divide by zero!") return a / b try: # This will trigger the exception result = divide_numbers(10, 0) except ValueError as e: print(f"Error: {e}") # You can also test with a valid division try: result = divide_numbers(10, 2) print(f"The result is: {result}") except ValueError as e: print(f"Error: {e}")输出:
Error: Cannot divide by zero!The result is: 5.0示例 3:使用 Division 处理 TypeErrordef safe_divide(a, b): try: result = a / b except ZeroDivisionError: print("Error: Cannot divide by zero.") return None except TypeError: print("Error: Invalid input type. Both inputs must be numbers.") return None return result # Test cases print(safe_divide(10, 2)) # Output: 5.0 print(safe_divide(10, 0)) # Output: Error: Cannot divide by zero. print(safe_divide(10, 'a')) # Output: Error: Invalid input type. Both inputs must be numbers.示例 4:使用try、except、else和finallydef read_file(file_path): try: # Attempt to open the file for reading file = open(file_path, 'r') # Try to read the file's contents data = file.read() except FileNotFoundError: # Handle the case of a missing file print(f"Error: The file '{file_path}' was not found.") except IOError: # Handle other I/O errors print("Error: An error occurred while reading the file.") else: print("File read successfully.") print() print(data) # If no exceptions, print the file's contents finally: # Check if the file variable exists if 'file' in locals(): # Ensure the file is closed file.close() print() print("File has been closed.") # Confirm the file closure # Example usage: # replace with a valid or invalid file path to testread_file("examples.txt")输出:
File read successfully.Hello, world! This is an example text file. It contains multiple lines of simple text. This file is used for demonstrating file reading in Python.File has been closed.