摘要:Python 使用一种称为 Exceptions 的机制来处理程序执行过程中可能出现的错误。发生错误时会引发异常,并且可以使用 try 块后跟 except 子句来捕获和处理异常。
错误处理是 Python 编程的一个关键方面,它允许开发人员编写健壮且有弹性的代码,这些代码可以优雅地处理意外情况或输入。
Python 使用一种称为 Exceptions 的机制来处理程序执行过程中可能出现的错误。发生错误时会引发异常,并且可以使用 try 块后跟 except 子句来捕获和处理异常。
用于根据特定条件在代码中手动引发异常。如果触发了 raise 语句,则控制权将移至相应的 except 块。如果引发异常,将跳过 else 块。以下是使用内置函数时会遇到的一些常见异常:
TypeError:将操作或函数应用于不适当类型的对象时引发。ValueError:当函数收到类型正确的参数但值不适当时引发。IndexError:尝试访问列表中范围之外的索引时引发。KeyError:找不到字典键时引发。zeroDivisionError:尝试除以零时引发。使用 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.当出现特定条件时,故意引发异常。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.0def 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.def 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.来源:自由坦荡的湖泊AI
免责声明:本站系转载,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与本站联系,我们将在第一时间删除内容!