examples: fix use of OSError

We generally shouldn't be raising OSError from user code since it
represents an error the bubbles up from the OS. Also, when handling
an OSError, we almost always want to check for a specific error code.
This commit is contained in:
David Lechner
2021-04-29 09:38:16 -05:00
parent 790fcfa66a
commit 3dad15ac11
2 changed files with 9 additions and 5 deletions
+1 -1
View File
@@ -13,7 +13,7 @@ device = I2CDevice(Port.S2, 0xD2 >> 1)
# For this device, we can read the Who Am I
# register (0x0F) for the expected value: 211.
if 211 not in device.read(0x0F):
raise OSError("Device is not attached")
raise ValueError("Unexpected I2C device ID")
# To write data, create a bytes object of one
# or more bytes. For example:
@@ -1,5 +1,6 @@
from pybricks.iodevices import PUPDevice
from pybricks.parameters import Port
from uerrno import ENODEV
# Dictionary of device identifiers along with their name.
device_names = {
@@ -41,10 +42,13 @@ for port in ports:
# Try to get the device, if it is attached.
try:
device = PUPDevice(port)
except OSError:
# No device found on this port.
print(port, ": ---")
continue
except OSError as ex:
if ex.args[0] == ENODEV:
# No device found on this port.
print(port, ": ---")
continue
else:
raise
# Get the device id
id = device.info()['id']