Search code examples
python-3.xerror-handlingtry-excepttracebackerror-messaging

How to still show error message when using try and except in Python


In my Python code, I have a function with "try" and "except" statement:

        for x in range (int(firstSocketEntry.get()), int(lastSocketEntry.get())+1): # Test will be done according to the range of the sockets
            for attempt in range (int(attemptEntry.get())):
                try:
                    print('Attempt: ' + str(attempt+1))
                    print('DUT: ' + str(x))
                    time.sleep(1)
                    client = HTTPClient('http://' + ipEntry.get() + port)
                    response = client.send(Request('test_is_alive', x), timeout=httpTimeOutEntry.get())
                    # response = request("http://" + ipEntry.get() + port, "test_is_alive", x)
                    time.sleep(1)
                    print(response.text)
                    print(response.data.result)
                    answer = response.data.result
             
                    logFile.write(time.strftime("%Y_%m_%d-%H_%M_%S\t\t") + str(x) + "\t\t" + str(answer) + "\t\t" + str(readVoltage()) + "\t\t" + str(readCurrent()) + "\n")               
                
                except:
                    print("Something went wrong!")
                    executeFunctionX()

                    
                else:
                    if (response.data.result==False):
                        print("\nAttempt " + str(attempt + 1) + " failed!")
                    else:
                        break
            else:
                print('\nAll attempts failed!')

If now something in the "try" statement goes wrong, the code continues at the "except" statement, which is the goal. How can I still get the error message (i.e.:

Traceback (most recent call last): File "C:\Users\pfra\AppData\Local\Programs\P six.raise_from(e, None) File "", line 3, in raise_from File "C:\Users\pfra\AppData\Local\Programs\P httplib_response = conn.getresponse())?

Because right now, I never know what exactly went wrong.

Any help is highly appreciated. Thanks a lot in advance. Regards


Solution

  • You will need to slightly modify your except:.

    See this:

    >>> try:
    ...     a
    ... except:
    ...     print("Something went wrong!")
    ... 
    Something went wrong!
    

    and compare it with:

    >>> try:
    ...     a
    ... except NameError as e:
    ...     print(f"What went wrong is {e}")
    ... 
    What went wrong is name 'a' is not defined
    

    If you do not know what exception your code may throw you can use except Exception as e:. However, it makes sense to invest the time to understand what exceptions your code may throw.