0

I would like to differentiate between different types of OSErrors in a try/except block. How do I determine the specific exception that caused the OSError.

If I run this code with "com9" open in another application, I capture the following error:

import serial
import sys
print(sys.version)
try:
    serA = serial.Serial(
        port='com9',
        baudrate='115200',
        parity='N',
        stopbits=1,
        bytesize=8,
        timeout=.05
    )
except OSError as e:
    print(e)

3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] could not open port 'com9': PermissionError(13, 'Access is denied.', None, 5)

If I run it with the port not connected I get the following:

3.11.2 (tags/v3.11.2:878ead1, Feb 7 2023, 16:38:35) [MSC v.1934 64 bit (AMD64)] could not open port 'com9': FileNotFoundError(2, 'The system cannot find the file specified.', None, 2)

How can I capture these in separate except clauses, or handle them individually?

ronk
  • 1
  • 1
    Does this answer your question? [Python: Catching specific exception](https://stackoverflow.com/questions/13531247/python-catching-specific-exception) – Marcelo Paco Apr 14 '23 at 16:57
  • Yes converting the exception to a string and searching the string does work, but I was hoping for a cleaner or more structural approach. This will work however (if e.args[0].find('PermissionError') != -1:) – ronk Apr 14 '23 at 17:16

0 Answers0