Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python script exits with exit code 255 despite try-except block

I am trying to build some exception handling into my Script before sending it out to users trial. To achieve this I'm trying to run try-except blocks to catch errors where I think they're likely to occur.

For example, the code uses an API to interact with another piece of software. This software relies on a hardware licence (USB dongle) to be installed in teh computer, otherwise the software cannot be accessed by Python and the script exits with Exit Code 255. Code example below.

    code-to-activate-licence
except Exception as e:
     warn-user-of-error

I would expect the try-except block to pick up the exit code and execute the except portion of the code. However, I assume that as the attempt to activate the licence does not seem to raise an error but instead gives a non-zero exit code it doesn't seem to be caught by the try-except block. Is there a way to catch this exit code before it actually exits the script?

like image 654
Quernon Avatar asked Sep 09 '26 16:09

Quernon


1 Answers

You are using except Exception as e: however the library is calling sys.exit() which raises a SystemExit which is of type BaseException rather than a standard Exception. Exception encompasses all non-system-exiting exceptions.

You need to explicitly catch SystemExit in order to interrupt it.

From the [docs]:

exception SystemExit

This exception is raised by the sys.exit() function. It inherits from BaseException instead of Exception so that it is not accidentally caught by code that catches Exception.

exception Exception

All built-in, non-system-exiting exceptions are derived from this class. All user-defined exceptions should also be derived from this class.

In code it would look something like:

try:
    somecode()
except Exception as e:
    do_something_with_exception(e)
except SystemExit as x:
    do_something_not_exit(x)
like image 186
MyNameIsCaleb Avatar answered Sep 11 '26 06:09

MyNameIsCaleb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!