【问题标题】:Properly structure try and except in Python functions在 Python 函数中正确构造 try 和 except
【发布时间】:2020-07-19 16:10:03
【问题描述】:

我正在尝试理解 Python 中 try 和 except 的概念,我知道这可以用来解决代码中的问题,而不会破坏应用程序的流程。

我正在开发一个具有客户端和开发人员端的应用程序。因此,我不想向用户显示确切的错误是什么,而是他们可以看到的代码,然后报告和发布它,我可以根据该代码找到错误。我不知道该怎么做。

我研究了主题Manually raising an exception in Python

我的程序有多个通过计算连接在一起的函数,即

def function_1(_input_):
   # do some jobs here get the result then, 
   result = function_2(result)
   return result

def function_2(_input_):
   # do some jobs here and get the result then, 
   result = function_3(result)
   return result

...

我想通过错误消息和导致问题的函数来捕捉在此过程中发生的错误。 我已经实现了这样的东西:

def function_1(_input_):
   try:
      # do some jobs here get the result then, 
      result = function_2(result)
   except Exception as e:
      print(e)
   return result

def function_2(_input_):
   try:
      # do some jobs here and get the result then, 
      result = function_3(result)
   except Exception as e:
      print(e)
   return result
...

【问题讨论】:

    标签: python exception try-except


    【解决方案1】:

    您可能想尝试 python 的 logging 功能。它是标准库的一部分。

    https://docs.python.org/3/howto/logging.html

    此外,日志输出仅向开发人员显示。您甚至可能会发现一些您可能会错过的错误或漏洞。

    【讨论】:

      【解决方案2】:

      try 子句的概念是为了避免你的程序崩溃。如果出现异常,程序将执行except子句下面的代码。如果您想获取异常并且不向用户显示它,我建议您将它们写入文件。

      def function_2(_input_):
         try:
            # do some jobs here and get the result then, 
            result = function_3(result)
         except Exception as e:
            with open('file_name', 'w') as f:
                f.write(e)
         return result
      

      【讨论】:

      • 感谢您的回答。我看到一些代码在错误上使用了一个类,然后在发生异常时引发了该类。类似于 ``` class MyErrorClass(Exception): def __init__(self, a): self.a = a `` 然后在 except 部分引发MyCustomError(e)。这是否也与本主题有关?
      • 这是一种构建自己的异常的方法,然后在课堂上重新处理该异常。你能接受我的回答吗?
      猜你喜欢
      • 2019-09-28
      • 2012-11-06
      • 2013-08-25
      • 2011-05-08
      • 2019-06-26
      • 2014-11-15
      • 1970-01-01
      • 1970-01-01
      • 2018-03-19
      相关资源
      最近更新 更多