Skip to main content
 首页 » 编程设计

python 基础 try catch 异常

2025年05月04日10yxwkf

我写了一段代码,它是转储从串行端口收集的数字,如下所示:

readoff = ser.readline() 

正确的读出格式如下:

a=' 213 -456 725' 

然后为了转储并进行一些计算,我将其分成 3 部分并将它们转换为整数,如下所示:

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

但有时我会从串行端口读取类似这样的内容:“2-264”,它不能变成整数。或者有时 readoff 不能被三整除。

这是我的示例错误:

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

我的目标是如果读数不正确(如果它不是 3 部分)(如果它不是正确的数字),跳过该读数并继续(读取另一个数据)。我怎样才能做到这一点 ?

感谢帮助

请您参考如下方法:

标准的 python try-catch 是:

try: 
    do_something_risky() 
 
except ExceptionName as exc: 
    do_something_else() 

指定要捕获的异常非常重要,否则您可能会捕获不需要的异常,这些异常应该冒泡,导致错误难以检测。

您可以捕获不同的异常并以不同的方式对其使用react:

try: 
    do_something_risky() 
 
except SomeException as exc: 
    do_this() 
 
except AnotherException as exc: 
    do_that() 

另外你可以添加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() 

在你的情况下

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