cih*_*gir 1 python exception try-catch
我写了一个代码,它倾倒从串口收集的数字,如下所示:
readoff = ser.readline()
Run Code Online (Sandbox Code Playgroud)
并且正确的读取格式如下:
a=' 213 -456 725'
Run Code Online (Sandbox Code Playgroud)
然后进行转储并进行一些计算,我将它分成3部分并将它们转换为整数,如下所示:
splitted=readoff.split()
if len(splitted) == 3 :
temparrayforx.append(int(splitted[0]))
temparrayfory.append(int(splitted[1]))
temparrayforz.append(int(splitted[2]))
Run Code Online (Sandbox Code Playgroud)
但有时从串口读取的内容如下:'2-264',它不能变成整数.或者有时读数不能被三个整除.
这是我的示例错误:
temparrayforx.append(int(splitted[0]))
ValueError: invalid literal for int() with base 10: '2-264'
Run Code Online (Sandbox Code Playgroud)
我的目标是如果读数不正确(如果它不是3部分)(如果它不是一个正确的数字),跳过该读数并继续(读取另一个数据).我怎样才能做到这一点 ?
感谢帮助
标准的python try-catch是:
try:
do_something_risky()
except ExceptionName as exc:
do_something_else()
Run Code Online (Sandbox Code Playgroud)
指定要捕获的异常非常重要,否则您可能会捕获应该冒出的不必要的异常,从而导致难以检测到错误.
您可以捕获不同的异常并以不同的方式对它们做出反应:
try:
do_something_risky()
except SomeException as exc:
do_this()
except AnotherException as exc:
do_that()
Run Code Online (Sandbox Code Playgroud)
此外,您可以添加else和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()
Run Code Online (Sandbox Code Playgroud)
try:
# Do the problematic thing
except ValueError as exc:
# Manage the exception
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
804 次 |
| 最近记录: |