Is Systemexit a Special Kind of Exception

SystemExit exception not seen as derived from BaseException

Well,
I don't know what happened but now it works.
Actually, due to a new way to extract my ip address, I changed the algorithm in order to get ip scanning data from a file and not from a windows command (arp -a is too limited for my purpose) so I modified the code as follows:

add_ip = None

# parse a previousely saved Angry-IP export
try:
with open ("current_ip_scan.txt", "r") as scan_file:
for line in scan_file:
line = line.upper()
line = re.sub(r':','-', line)
if (re.search(add_mac, line)) is not None:
add_ip = re.findall('(([0-9]{2,3}\.){3}[0-9]{3})',line)[0][0] # to get the first element of the tuple
except FileNotFoundError:
print("*** Angry-IP export not available - do it into 'current_ip_scan.txt' in order to find the matching IP address ***")
raise SystemExit("failure retrieving interface's IP address")

if add_ip is not None:
# check that the ip address is a valid IP
if(re.match('(([0-9]{2,3}\.){3}[0-9]{3})', add_ip)) is not None:
print("@IP =\t", add_ip) # log matching IP
else:
raise SystemExit("failure retrieving interface's IP address")
else:
#sys.exit("failure retrieving interface's IP address")
raise SystemExit("failure retrieving interface's IP address")

return add_ip

I tried both, sys.exti and raise SystemExit and both now work (?).
@kevin @ sanket: Thank you for your help and your time

Alexandre

Using sys.exit or SystemExit; when to use which?

No practical difference, but there's another difference in your example code - print goes to standard out, but the exception text goes to standard error (which is probably what you want).

Difference between calling sys.exit() and throwing exception

sys.exit raises a SystemExit itself so from a purely technical point of view there's no difference between raising that exception yourself or using sys.exit. And yes you can catch SystemExit exceptions like any other exception and ignore it.

So it's just a matter of documenting your intent better.

PS: Note that this also means that sys.exit is actually a pretty bad misnomer - because if you use sys.exit in a thread only the thread is terminated and nothing else. That can be pretty annoying, yes.

Can't catch SystemExit exception Python

As documented, SystemExit does not inherit from Exception. You would have to use except BaseException.

However, this is for a reason:

The exception inherits from BaseException instead of StandardError or Exception so that it is not accidentally caught by code that catches Exception.

It is unusual to want to handle "real" exceptions in the same way you want to handle SystemExit. You might be better off catching SystemExit explicitly with except SystemExit.



Related Topics



Leave a reply



Submit