Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在编写许多try-except块时,是否有最佳实践可遵循?_Python_Python 3.x_Error Handling_Error Logging_Try Except - Fatal编程技术网

Python 在编写许多try-except块时,是否有最佳实践可遵循?

Python 在编写许多try-except块时,是否有最佳实践可遵循?,python,python-3.x,error-handling,error-logging,try-except,Python,Python 3.x,Error Handling,Error Logging,Try Except,举一个简单的例子来说明我的意思,假设我有3个.py文件(file1、file2、file3),它们为我执行不同的任务,我需要在每个步骤记录错误,这是正确的方法还是可以遵循其他最佳实践 file1.py: def some_function(some_var): try: if some_var == 0: raise ValueError("Can't be zero") else: re

举一个简单的例子来说明我的意思,假设我有3个.py文件(file1、file2、file3),它们为我执行不同的任务,我需要在每个步骤记录错误,这是正确的方法还是可以遵循其他最佳实践

file1.py:

def some_function(some_var):
    try:
        if some_var == 0:
            raise ValueError("Can't be zero")
        else:
            return 1
    except ValueError:
        raise
file2.py

import file1

def some_other_fn(some_other_var):
    try:
        return file1.some_function(some_other_var)
    except:
        raise

file3.py

import file2
import traceback

try:
    res = f2.some_other_fn(0)
except:
    # handle err
    print(traceback.format_exc())
当然,另一个问题是,当我重新提出我在file1中可能遇到的许多类型的错误时,(比如说4+),我应该在不同的文件中捕获相同的4个错误吗?这似乎是多余的代码。是否有一种方法可以让我知道在file3中file1中发生了什么样的错误,而无需在file2和file3中明确写入除ValueError之外的


请注意,无法在file1和file2中退出,file3是主控制流,其他功能必须返回到它。

您似乎不了解try except是如何工作的。请重复您的教程以获取示例。由于基代码不可能引发运行时错误,因此try-except构造是不合适的。手动引发异常,将其包装在try-except块中,仅仅重新引发相同的异常,这是愚蠢的

相反:

def some_function(some_var):
    if some_var == 0:
        raise ValueError("Can't be zero")
    else:
        return 1
import file1

def some_other_fn(some_other_var):
    return file1.some_function(some_other_var)
类似地,您的下一个函数有一个函数为null的try-except块。您没有以任何方式专门处理异常,因此您所做的只是复制默认的异常传播——运行时系统已经这样做了

相反:

def some_function(some_var):
    if some_var == 0:
        raise ValueError("Can't be zero")
    else:
        return 1
import file1

def some_other_fn(some_other_var):
    return file1.some_function(some_other_var)
在最后一个块中,您最终正确使用了try-except:

  • 执行可能引发异常的代码
  • 如果是,那么您将对异常做出反应

  • 对于更多的布朗尼点,文件3中的except语句应该只包含except VALUETERROR,是的——我允许更广泛的应用,但你很正确,我至少应该提出(嗯)这个点。我明白了,我理解try except的工作原理是错误的。很好的回答。