CheezGuy
CheezGuy

Reputation: 39

Python try/except not stopping errors

My following code was designed to handle exceptions and switch serialport if nothing was found.

try:
    serial_port = '/dev/cu.usbserial-10'
except:
    try: 
        serial_port = '/dev/cu.usbserial-110'
    except:
        print("Unable to find sensor. Try again")

However, it is not actually handling exceptions, and still lets them get through to the console:

Traceback (most recent call last):
  File "/Users/username/Library/Python/3.10/lib/python/site-packages/serial/serialposix.py", line 322, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: '/dev/cu.usbserial-10'

I have set it in the code so that if there is no /dev/cu.usbserial-10, it tries serial-110, and if that's not there, it prints something, but it does not print ever.

Edit:

I am using pyserial so the serial_port assignment attempts to find a file location. '/dev/cu.usbserial-10' is one of the USB ports on my computer.

The error does show that its at line 322, but my file is not >100 lines long.

More context:

import serial

serial_port = 0

try:
    serial_port = '/dev/cu.usbserial-10'
except:
    try:
        serial_port = '/dev/cu.usbserial-110'
    except:
        print("no")


baud_rate = 115200

ser = serial.Serial(serial_port, baud_rate) # serial data, non-usable

try:
    while True:
        rawdata = ser.readline().decode().strip() # raw string data from serial
        print(rawdata)

This is quite literally my whole file, and when usbserial-10 is found, it does work.

Upvotes: 0

Views: 126

Answers (2)

ShadowRanger
ShadowRanger

Reputation: 155574

You didn't wrap the opening of the port in try/except, and that's what's erroring. String assignment is essentially infallible, no exceptions will ever occur there. An idiomatic way to achieve your goal would be to replace:

import serial

serial_port = 0

try:
    serial_port = '/dev/cu.usbserial-10'
except:
    try:
        serial_port = '/dev/cu.usbserial-110'
    except:
        print("no")


baud_rate = 115200

ser = serial.Serial(serial_port, baud_rate) # serial data, non-usable

with:

import serial
import sys

baud_rate = 115200

# Loop over possible ports until we open one successfully, or all fail
for serial_port in ('/dev/cu.usbserial-10', '/dev/cu.usbserial-110'):
    try:
        ser = serial.Serial(serial_port, baud_rate)
        break  # If opening the serial port succeeded, we're done, move on to using it
    except OSError as e:
        print(f"Failed to open {serial_port!r}", file=sys.stderr)
else:
    sys.exit(f"Couldn't not open any serial ports, exiting...")

try:
    while True:
        rawdata = ser.readline().decode().strip() # raw string data from serial
        print(rawdata)
except OSError:
    # Handle errors as desired

Upvotes: 0

Avijit Bhuin
Avijit Bhuin

Reputation: 26

according to the posted code you're trying to execute some kind of function that opens a serial port according to the assigned text.

try:
serial_port = '/dev/cu.usbserial-10' 
    #you're only assigning the value to a variable . you actually need to call the function that youre testing with that variable here
except:
    try: 
        serial_port = '/dev/cu.usbserial-110'
    except:
        print("Unable to find sensor. Try again")

here is a sample code:

try:
serial_port = '/dev/cu.usbserial-10'
response=open_serial_port(serial_port) #assuming 'open_serial_port' is the function name.
except:
    try: 
        serial_port = '/dev/cu.usbserial-110'
        response=open_serial_port(serial_port) #assuming 'open_serial_port' is the function name.
    except:
        print("Unable to find sensor. Try again")

this is an example of how you an fix it.

here is the updated code you provided:

import serial

serial_port = 0
baud_rate = 115200

try:
    serial_port = '/dev/cu.usbserial-10'
    ser = serial.Serial(serial_port, baud_rate) # serial data, non-usable
except:
    try:
        serial_port = '/dev/cu.usbserial-110'
        ser = serial.Serial(serial_port, baud_rate) # serial data, non-usable
    except:
        print("no")

try:
    while True:
        rawdata = ser.readline().decode().strip() # raw string data from serial
        print(rawdata)

except:
    pass

Upvotes: 0

Related Questions