简体   繁体   中英

python basic try catch exception

i wrote a code which is dumping numbers which is collected from serial port read as follows:

readoff = ser.readline()

and the proper format of readoff is follows:

a=' 213 -456 725'

and then for dumping and making some calculations im splitting it to 3 part and turning them to integer as follows:

 splitted=readoff.split()
 if len(splitted) == 3 :    
        temparrayforx.append(int(splitted[0]))
        temparrayfory.append(int(splitted[1]))
        temparrayforz.append(int(splitted[2]))

but sometimes from the serial port im reading something like: '2-264' which cannot turned into a integer. or sometimes readoff is not divisible to three.

here is my sample error:

temparrayforx.append(int(splitted[0]))
ValueError: invalid literal for int() with base 10: '2-264'

my goal is if the reading is not correct(if its not 3 part)(if its not a proper number), skip that readoff and go on(read another data). how can i do that ?

thanks for help

The standard python try-catch is:

try:
    do_something_risky()

except ExceptionName as exc:
    do_something_else()

It is very important to specify the exceptions you want to catch , otherwise you might catch unwanted exceptions that should bubble up, resulting in errors difficult to detect.

You can catch different exceptions and react in a different way to them:

try:
    do_something_risky()

except SomeException as exc:
    do_this()

except AnotherException as exc:
    do_that()

Additionally you can add else and finally

try:
    do_something_risky()

except ExceptionName, AnotherPossibleException as exc:
    do_something_else()

else:
    do_something_when_no_exception_raised()

finally:
    # Useful for cleaning up
    do_something_no_matter_what_happens()

In your case

try:
    # Do the problematic thing
except ValueError as exc:
    # Manage the exception

You should catch the specific exception that's being raised, ValueError in this case:

try:
    temparrayforx.append(int(splitted[0]))
except ValueError as e:
    print e

It's important to catch a specific error type so you don't accidentally catch lots of unexpected errors - like if splitted is empty, an IndexError would be raised. A bare 'except:' or 'except Exception:' would hide that from you.

In your case, since you want to catch a couple of different error cases (line doesn't have enough parts, value isn't a number) you can either catch both exception types in the same except clause or have two different except clauses - for example if you need to do different things with each problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM