正确构造Python函数中的try和except

正确构造Python函数中的try和except,python,exception,try-except,Python,Exception,Try Except,我试图理解Python中try和except的概念,我知道这可以用来解决代码中的问题,而不会中断应用程序的流程 我正在开发一个有客户端和开发者端的应用程序。因此,我不想向用户显示确切的错误是什么,而是一个他们可以看到的代码,然后报告并发布,我可以根据该代码找到错误。我不知道该怎么做 我研究了这个话题 我的程序有多个通过计算连接在一起的函数,即 def function_1(_input_): # do some jobs here get the result then, resu

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

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

我研究了这个话题

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

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
...

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

您可能希望尝试python的日志记录功能。它是标准库的一部分


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

谢谢您的回答。我看到一些代码使用一个类来处理错误,然后在异常发生时引发该类。类似于``class MyErrorClass(Exception):def\uu init\uuuu(self,a):self.a=a``的东西,然后在except部分中引发
MyCustomError(e)
。这也与本主题相关吗?这是一种构建您自己的异常的方法,然后在类中重新处理该异常。你能接受我的回答吗?