-1

I am trying to understand the concept of try and except in Python and I know that this can be used to address the issue in the code with out breaking the flow of the application.

I am working on a application that has a client and a developer side. Therefore, I do not want to show the users what was the exact error but instead a code that they can see and then report and issue with it and I can find the error based on that code. I am not able to figure out how to do this.

I looked into the topic Manually raising an exception in Python.

My program is having multiple functions that are connected together trough their calculations, i.e.

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

...

I want to catch errors that happens during this process with error message and the function that caused the problem. I already implemented something like this:

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
...
LoneWolf
  • 79
  • 6

2 Answers2

1

You might want to try logging feature of python. It's part of the standard library.

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

Also the logging output is only shown to the developer. You might even find some errors or loopholes that you would otherwise miss.

Amit Kumar
  • 804
  • 2
  • 11
  • 16
0

The concept of try clause is to avoid the crash of your program. If an exception appears, the program will execute the code below except clause. IF you want to grab exceptions and do not show it to users I suggest you write them to a file.

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
Aleksander Ikleiw
  • 2,549
  • 1
  • 8
  • 26
  • Thank you for your answer. I saw some codes that used a class on top for their errors and then raised that class when an exception occurred. Something like ``` class MyErrorClass(Exception): def __init__(self, a): self.a = a ``` and then raise ```MyCustomError(e)``` in except part. Does this relate to this topic as well? – LoneWolf Jul 19 '20 at 16:20
  • it is a way to build your own exception, then in class, that exception was reprocessed. Can you please accept my answer? – Aleksander Ikleiw Jul 19 '20 at 16:21