python - Python按顺序运行函数;如果失败,请停止

标签 python python-3.x function error-handling

按顺序运行功能的最佳实践是什么?
我有4个功能,如果前一个功能失败,请不要运行以下功能。在每个函数中,当发生异常时,我都设置global errorerror = 1。然后在主要情况下,我只使用if语句检查error的值。我认为应该有一个更好的方法。

def main():
    engine = conn_engine()
    if error == 0:
        process_sql()
    if error == 0:
        append_new_rows_to_prod()
    if error == 0:
        send_email_log()

最佳答案

规范的方法是在函数内引发异常。例如:

def process_sql():
  # Do stuff
  if stuff_failed:
    raise ProcessSQLException("Error while processing SQL")

def append_new_rows_to_prod():
  # Do other stuff
  if other_stuff_failed:
    raise AppendRowsException("Error while appending rows")

def main():
    engine = conn_engine()
    try:
      process_sql()
      append_new_rows_to_prod()
      send_email_log()
    except ProcessSQLException, AppendRowsException as e:
      # Handle exception, or gracefully exit

关于python - Python按顺序运行函数;如果失败,请停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64057331/

相关文章:

python - Pandas Pivot 更改列的顺序

python - 如何对 pandas crosstab 中的行求和并制作一个新的 crosstab?

python - Pandas DataFrame 合并选择更高的值

python - 为什么对象在 for 循环中加速?

python,访问psycopg2形式的def?

c# - 如何将 Python 版本 3 与 .Net 集成

c - 为什么我的计算字母和数字的程序没有运行?

function - Swift 中的函数和方法有什么区别?

function - 如何为函数/过程创建别名?

python - OS X 10.8 上的浅蓝 : method signature mismatch