Conditional except statements in Python - python

Is there a way to make an except statement conditional - in other words, only catch a type of exception if the condition is true? This is the idea I have, but it seems like it won't work
try:
<code>
if condition == True:
except Exception as e:
<error handling>

No, you can't do that. What you can do is catch the error then check the condition inside the except block and re-raise if necessary:
except Exception as e:
if not condition:
raise

Not like that, but I find this to be the cleanest solution
try:
<code>
except Exception as e:
if condition:
<error handling>
else:
raise # re raises the exception

You could use different exceptions for each case and catch them seperately:
import random
class myException_1(Exception):
pass
class myException_2(Exception):
pass
try:
a = random.randint(0,10)
if a % 2 == 0:
raise myException_1("something happened")
elif a % 3 ==0:
raise myException_2("something else happened")
else:
print("we made it!")
except myException_2 as e:
print("a was divisible by 3")
print(e)
except myException_1 as e:
print("a was divisible by 2")
print(e)

Related

Python if error in a loop continue loop from next iteration

I have such code:
for i in range(0,5):
try:
print(f"opened some_file_{i}")
except Exception as e:
print(f"error opening some_file_{i}")
return
print(f"i = {i}")
After exception, I need contuinue the loop from the next iteration, but not continue code (print(f"i = {i}")
How can I do it?
I tried to use a break, continue, pass statements and return
Sorry, continue works
for i in range(0,5):
try:
print(f"opened some_file_{i}")
except Exception as e:
print(f"error opening some_file_{i}")
continue
print(f"i = {i}")
So if I had an exception, continue will skip this loop iteration
If you have handled the exception properly it should continue on to the next iteration. You do not require break, continue, pass or return statements.
When you try to break or return the control will exit out of the loop/ function.
Example:
for i in range(0,5):
try:
print("Hello {}".format(i))
if i == 3:
raise Exception("Wrong file path error")
except Exception as e:
print(e)
Output

Continue executing a for loop is a specific system exit is raised in Python

I have a function that has multiple sys.exit() exceptions. I am calling the function iteratively and want my loop to continue if a certain sys.exit() is raised while error out for all others.
The sample code can be something like:
def exit_sample(test):
if test == 'continue':
sys.exit(0)
else:
sys.exit("exit")
list = ["continue", "exit", "last"]
for l in list:
try:
exit_sample(l)
except SystemExit:
print("Exception 0")
In the current form, the code will not error out but will print 'Exception 0' every time. I want it to not error out the first time, and then exit when l = "exit". How can that be done?
You can catch the exception, check if it is the one that justifies continue and re-raise it if it does not.
import sys
def exit_sample(test):
if test == 'continue':
sys.exit(0)
else:
sys.exit("exit")
lst = ["continue", "exit", "last"]
for l in lst:
try:
exit_sample(l)
except SystemExit as ex: # catch the exception to variable
if str(ex) == "0": # check if it is one that you want to continue with
print("Exception 0")
else: # if not re-raise the same exception.
raise ex
Store the exception in a variable and check if the code (or other characteristics) matches your condition for continuing your code. I modified your code such that it will continue if the exit code is 0 and otherwise re-raises system exit
import sys
def exit_sample(test):
if test == 'continue':
sys.exit(0)
else:
sys.exit("exit")
list = ["continue", "exit", "last"]
for l in list:
try:
exit_sample(l)
except SystemExit as exc:
if exc.code == 0:
print("continuing")
else:
# raise previous exception
raise
What you want is to convert the exception to a string and compare that with "exit". After seeing if it works, you can remove the print statement.
import sys
def exit_sample(test):
if test == 'continue':
sys.exit(0)
else:
sys.exit("exit")
list = ["continue", "exit", "last"]
for l in list:
try:
exit_sample(l)
except SystemExit as error:
print(error)
if str(error) == "exit":
sys.exit("foo")

Python exception: execute code if a specific exception is raised or else

Let's say I have the following code, that assign 1 and print it in case the value is None or not negative.
value = None
class NegativeNumber(Exception):
pass
class NotFound(Exception):
pass
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
except NotFound:
value = 1
print(value)
else:
value = 1
print(value)
Is there a way to avoid repeat twice to assign value=1 and print it?
It would be ideal something like except NotFound or else, but I have not found anything similar in python.
There is no except ... or else: construct. Suppress the exception inside the try block to trigger the else block for the exception as well:
try:
try:
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NotFound:
pass # suppress exception
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)
Instead of using try/except to suppress the exception, contextlib.suppress can be used instead. This can make the intention clearer, as it explicitly names how the exception is handled.
try:
with suppress(NotFound):
if value is None:
raise NotFound
elif value < 0:
raise NegativeNumber
except NegativeNumber:
print("Error: negative number")
else:
value = 1
print(value)

Python, distinguishing custom exceptions

fairly new to Python here. Have this code:
def someFunction( num ):
if num < 0:
raise Exception("Negative Number!")
elif num > 1000:
raise Exception("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except Exception:
print "This was a negative number but we didn't crash"
except Exception:
print "This was a big number but we didn't crash"
else:
print "All tests passed and we didn't crash"
I originally used raise "Negative Number!" etc but quickly discovered that this was the old way of doing things and you have to call the Exception class. Now it's working fine but how do I distinguish between my two exceptions? For the code below it's printing "This was a negative number but we didn't crash". Any pointers on this would be great. Thanks!
you need to create your own exception classes if you want to be able to distinguish the kind of exception that happened. example (i inherited from ValueError as i think this is the closest to what you want - it also allows you to just catch ValueError should the distinction not matter):
class NegativeError(ValueError):
pass
class BigNumberError(ValueError):
pass
def someFunction( num ):
if num < 0:
raise NegativeError("Negative Number!")
elif num > 1000:
raise BigNumberError("Big Number!")
else:
print "Tests passed"
try:
someFunction(10000)
except NegativeError as e:
print "This was a negative number but we didn't crash"
print e
except BigNumberError as e:
print "This was a big number but we didn't crash"
print e
else:
print "All tests passed and we didn't crash"

Python: Rerun try-except loop

I'm trying to rerun a try-except loop each time there is an error and only break when there is no error.
loop = True;
while loop == True:
try:
for i in data_names:
#do something
except Exception, e:
e = str(e)[0:100];
parse_error_list.append(str(e)[str(e).rindex(':')+2:str(e).rindex(':')+4]);
if len(e) == 0:
loop = False;
As a sanity check, will the following allow me to exit the loop if and only if there is no error?
EDIT: Is the answer? If so, is this the most efficient implementation? ...
loop = True;
while loop:
try:
for i in data_names:
#do something
except Exception, e:
e = str(e)[0:100];
parse_error_list.append(str(e)[str(e).rindex(':')+2:str(e).rindex(':')+4]);
if e:
loop = False;
The neatest solution would probably resemble:
while True:
try:
for i in data_names:
#do something
except Exception, e:
#log or otherwise handle exception
else:
break

Categories

Resources