Python中异常处理:10大常见异常及其处理实例

原创 悠悠 2025-02-24 12:30 41阅读 0赞

在Python编程中,异常处理是一种机制,用于在程序执行过程中遇到错误时进行适当的处理。以下是Python中10种常见的异常以及相应的处理实例:

  1. ZeroDivisionError:当除数为零时引发。示例:

    1. try:
    2. division = 1 / 0
    3. except ZeroDivisionError as e:
    4. print(f"Error: {e}. Avoid dividing by zero.")
  2. TypeError:当操作或函数应用于不合适的类型时引发。示例:

    1. try:
    2. int_string = "32"
    3. float_number = int_string + ".5"
    4. print(float_number)
    5. except TypeError as e:
    6. print(f"Error: {e}. Type conversion may be required.")
  3. ValueError:当数据不符合预期格式时引发。示例:

    1. try:
    2. email = "invalid-email"
    3. validate_email(email)
    4. except ValueError as e:
    5. print(f"Error: {e}. Email validation failed.")
  4. KeyError:当试图访问字典中不存在的键时引发。示例:

    1. try:
    2. my_dict = {"name": "Alice", "age": 25}
    3. print(my_dict["address"]))
    4. except KeyError as e:
    5. print(f"Error: {e}. Key 'address' not found in dictionary.")
  5. IndexError:当尝试访问列表中的某个索引超出范围时引发。示例:

    1. try:
    2. my_list = [1, 2, 3]
    3. print(my_list[4])
    4. except IndexError as e:
    5. print(f"Error: {e}. Index '4' is out of range for list.")
  6. FileNotFoundError:当尝试打开一个不存在的文件时引发。示例:

    1. try:
    2. file_to_open = "nonexistent_file.txt"
    3. with open(file_to_open, 'r') as f:
    4. print(f.read())
    5. except FileNotFoundError as e:
    6. print(f"Error: {e}. File 'nonexistent_file.txt' not found.")
  7. IOError:这是FileNotFoundError的父类,当文件操作遇到更广泛的错误时引发。示例:

    1. try:
    2. file_to_open = "broken_file"
    3. with open(file_to_open, 'r') as f:
    4. print(f.read())
    5. except IOError as e:
    6. print(f"Error: {e}. File 'broken_file' could not be opened due to an error.")
  8. SystemExit:在Python中,当调用os.system()sys.exit()时会引发。示例:

    1. try:
    2. exit_message = "Program gracefully stopped."
    3. os.system("echo " + exit_message)
    4. sys.exit(0) # Normal exit, no error code
    5. except SystemExit as e:
    6. print(f"Error: {e}. Program was terminated via 'sys.exit()'.")
  9. Timeout:当使用time.sleep()或其他可能导致阻塞的操作时,可能会遇到超时问题。示例:

    1. try:
    2. time_to_wait = 5 # seconds
    3. sleep(time_to_wait)
    4. print("Action completed within the timeout.")
    5. except TimeoutError as e:
    6. print(f"Error: {e}. Action timed out after '{time_to_wait}' seconds.".format(time_to_wait)))
  10. SyntaxError:当Python解析器遇到语法错误时,会引发此错误。示例:

    1. try:
    2. invalid_code = "print('Hello, World!')\ninvalid_line"
    3. exec(invalid_code) # Raises SyntaxError
    4. except SyntaxError as e:
    5. print(f"Error: {e}. Invalid syntax found in code.".format(invalid_code)))

以上就是Python中常见异常及其处理的示例。在实际编程中,根据具体需求和场景进行异常处理是非常重要的。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,41人围观)

还没有评论,来说两句吧...

相关阅读