-1

This is a function of my project (which I cannot share in full) for work which is constantly failing. We're working on a multi-use system for Data Acquisition and motor control using a Raspberry Pi. I set up a large try:/except: system for both debugging and if our users give faulty data somehow.

The function iterates successfully through data provided, setting 0b0 and 0b1 for each text '0' or '1' fed to it. However, once it successfully converts to "true" binary, it fails when iterating through groups of eight to convert them (this is because, for some reason, other attempts with int(x, base) have thrown the TypeError). The error thrown is not any of the following:

  1. TypeError
  2. ArithmeticError
  3. RuntimeError (which it should fall back to, right?)
  4. EnvironmentError
  5. UnboundLocalError
  6. LookupError
  7. ValueError
  8. IndexError

Running the for i in range(0, floor(length / 8), 1): and subcode also throws an error, but it is not described - it just fails. I have been debugging this singular function for a few days, and this seems to be the last problem, but I honestly have no idea why it is failing. The function, convertStates(data), is below.

def convertStates(data):
    # Converts binary states (0/1) in any format (due to built-in functions not working) to text.
    n = 0
    dmn = str(data)
    dat = '0b0'
    datFirst = True
    try:
        for i in dmn:
            toapp = '0b0' if (i == 0) else '0b1'
            if (datFirst):
                dat = toapp
                datFirst = False
            else:
                dat.join(toapp)
    except:
        print("Error: Failed to append binary values to list.")
        exit()
    try:
        length = len(dat)
    except:
        print("Error acquiring length of binary data")
        exit()
    try:
        for i in (range(0, floor(length / 8), 1)):   <<<< SOMETHING HERE
            try:
                temp = int(dat[i*8:i*8+8],2) # this is perfectly fine
            except:
                print("Error with byte storage")
            try:
                a = temp.decode("utf-8")
                print(str(a))
            except:
                print("Error with decoder")
            try:
                n += chr(a)
            except:
                print("Error with character converter")
    except ValueError:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary->string due to value mismatch.")
        exit()
    except TypeError:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary->string due to value type mismatch.")
        exit()
    except UnboundLocalError:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary->string due to unbound variable(s).")
        exit()
    except IndexError:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary->string due to an index call for nonexistent value.")
        exit()
    except ArithmeticError:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary->string due to math error.")
        exit()
    except LookupError:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary->string due to lookup error.")
        exit()
    except:
        print("Exception occurred in 'convertStates(data)' function!")
        print("Error: Could not convert binary bytewise to string.")
        exit()
    return n

As I stated earlier, the try:/except: systems have been put in place to identify the error on my part, and to lay groundwork for end-user problem solving.

I have looked at upwards of ten different posts surrounding this, to no avail. I cannot find the error with this, and I had to set it up this way because int(x, base) could not convert anything - refer to this post here (Convert string to binary in python), which is one solution I tried to use.

As for the exit() calls, it's so we don't get an endless loop of twenty exceptions piling atop each other, as this function is one called in part of a loop.

What am I doing wrong, and how do I fix it? Was it some stupid little thing I should've noticed (Python is not my top language), or is it something else entirely? Any help is appreciated. This is just driving me slightly insane - nothing I've looked at can solve it or the problems that caused me to make this.

EDIT: People have said to put the callback w/o the bare except:, and as I said earlier, it gives nothing. It just fails. No error code, no traceback, nothing. I am being honest here - removed the except: from test code and from loop. All it does is exit, when it should continue running.

Evan C.
  • 1
  • 3
  • 2
    seriously..? If you're not doing anything with the exception, then let it escape. The traceback will contain all the information you're looking for. – thebjorn Jun 25 '20 at 17:39
  • 2
    It would help if you showed the traceback – roganjosh Jun 25 '20 at 17:40
  • 1
    First, any time you use `except` with no explicit exception, it's a catch-all. If you want to know what the error is, remove the catch-all except clauses and see what stack trace is bubbled up by the interpreter. Python error print outs are usually very self-explanatory as well as almost always printing the type of error/exception as the first thing on the last line of the trace. – gallen Jun 25 '20 at 17:40
  • 3
    You have put a LOT of effort into making it impossible to tell what's going wrong with this code. Get rid of all those bare `except:`s, all they're doing is throwing away the error details. – jasonharper Jun 25 '20 at 17:40
  • 3
    There's a lot of cruft here. Why do you need to `print ("Exception occurred in 'convertStates(data)' function!")` for instance? The traceback will tell the user where the exception was thrown. – roganjosh Jun 25 '20 at 17:42
  • 1
    What do you mean by "it just fails"? Do you mean the process crashes? Do you get a non-zero exit code? Or are you asking us to debug the logic of that routine for you? – MEE Jun 25 '20 at 17:55

1 Answers1

1

None of this makes sense. Either:

  1. You're the user and you need to understand how to read tracebacks
  2. You've assumed too much incompetency on behalf of your user

It's pointless to catch individual exceptions, gobble up the traceback, and just exit the program. Nothing is resolved from this (your exception handling doesn't allow the program to continue), and now the user just gets a print-out that tells them nothing particular. It's counter-productive, actually. You've just made it harder for anyone to debug.

This is easy to illustrate:

def to_int(something):
    return int(something)

a = 2
b = '3.4'

lst = [a, b]

for item in lst:
    to_int(item)

Gives:

Traceback (most recent call last):

  File "D:\github\beatroute_test\untitled1.py", line 10, in <module>
    to_int(item)

  File "D:\github\beatroute_test\untitled1.py", line 2, in to_int
    return int(something)

ValueError: invalid literal for int() with base 10: '3.4'

versus:

def to_int(something):
    return int(something)

a = 2
b = '3.4'

lst = [a, b]

for item in lst:
    try:
        to_int(item)
    except ValueError:
        print("There's a ValueError!")

In the second case, I have no idea which value caused it.

roganjosh
  • 12,594
  • 4
  • 29
  • 46
  • 1
    Thank you for your amazingly constructive and helpful response! The actual problem was nested within a failure to use ```from math import floor```, not with the try/catch loop. Because of your useful feedback, though, I will spend some time to clean it up. In the mean time, I'll remind myself to avoid asking questions here, because I do understand how to read tracebacks - I'm not the tech-illiterate end user. – Evan C. Jun 25 '20 at 18:06
  • @EvanC. I'm not impressed nor amused by your sarcasm. It was not my intention to insult you, but I'm saying that the exception handling is flawed even outside of that issue. If you want to be sarcastic in your response, fine. I'm trying to be objective and that chain of `except`s is broken – roganjosh Jun 25 '20 at 18:18
  • @EvanC. I edited to illustrate, if you care. You exception handlers rob users of vital info – roganjosh Jun 25 '20 at 18:28