Exit script from inside of try-catch block in Python 3 - python

I'm trying to exit a script from inside a try: except: block except it just goes on to the exception case.
None of these...
try:
exit()
except:
pass()
try:
quit()
except:
pass
import sys
try:
sys.exit()
except:
pass
...exit my script, they just go on to the except case.
How would I exit my script from inside one of these blocks?

All of these examples raise the SystemExit exception and you are catching that exception, a blank except clause will catch all exceptions.
This is the reason why you should always specify the exception you intend to catch or at least use except Exception eg
try:
exit()
except Exception:
pass
try:
quit()
except Exception:
pass
import sys
try:
sys.exit()
except Exception:
pass
With that change in place, all of you examples will cause your Python app to exit

Related

Python: catch Exception or keyboard interrupt

I have the following code:
import time
try:
time.sleep(3)
raise Exception('error')
except Exception or KeyboardInterrupt:
print(">>> Error or keyboard interrupt")
I want to catch either error or key board interrupt. But currently, it catches only Exception, keyboard interrupt is not handled.
If I remove Exception and leave only Keyboard interrupt, it catches only keyboard interrupt.
If I remove KeyboardInterrupt and leave only Exception, it catches only Exception.
Is there a way to catch both ?
If you want to handle the two cases differently the best way of doing this is to have multiple except blocks:
import time
try:
time.sleep(3)
raise Exception('error')
except KeyboardInterrupt:
print("Keyboard interrupt")
except Exception as e:
print("Exception encountered:", e)
Mind the order!
According to https://docs.python.org/3/tutorial/errors.html#handling-exceptions
you can use
except (RuntimeError, TypeError, NameError):
import time
try:
time.sleep(3)
raise Exception('error')
except (Exception, KeyboardInterrupt):
print(">>> Error or keyboard interrupt")

Break the try and go directly to the exception if condition is false

I have a complex code in python with condition inside try:
try:
if condition is True: execute the code
else: go to exception and don't execute the code
except:
execute the except statement
I want to exit the try statement if condition is met
Just manually raise an exception:
try:
if condition:
your code
else:
raise Exception('Exception message')
except:
# except code here

Stop program from running after try / except python

I made a program that takes values from treeview and calculate something when button is pressed. I put try / except statement inside that function.
def SumAll():
try:
#do something (calculate)
except ValueError:
Error=messagebox.showinfo("Enter proper values")
pass
The problem is, program keeps running when messagebox.showinfo appears, and it gives the ValueError.
How can I fix that, and how can I put more than one error exception (IndexError, etc)?
You can re-raise the exception, and if the exception reaches the top of the stack, the program will exit
try:
#do something (calculate)
except ValueError:
Error=messagebox.showinfo("Enter proper values")
raise
Or you can manually call sys.exit
import sys
try:
#do something (calculate)
except ValueError:
Error=messagebox.showinfo("Enter proper values")
sys.exit(1)
To catch more than on in the same handler, you can do something like
try:
#do something (calculate)
except (IndexError, ValueError):
Error=messagebox.showinfo("Enter proper values")
raise
or if you want different handlers you can have
try:
#do something (calculate)
except IndexError:
Error=messagebox.showinfo("Some message")
raise
except ValueError:
Error=messagebox.showinfo("Enter proper values")
raise
You can catch multiples by:
try:
k = input().split()[2]
i = int(k[0])
except (IndexError, ValueError) as e:
print(e) # list index error: 'Hello World', Value error: 'Hello World Tata'
else:
print("no error")
this will guard against inputs that split to less then 3 items '5 a' as well as against int conversion errors: 'Hello World Is A Cool Thing' (`'Is'`` is not an integer).
Use How to debug small programs (#1) to debug through your real program, the error you get above this except is caught. You probably get a resulting error somewhere else because somethings not right with the return of your function.

Catch all exceptions except user abort

I have a script that catches all exceptions, which works great unless I want to abort the script manually (with control + c). In this case the abort command appears to be caught by the exception instead of quitting.
Is there a way to exclude this type of error from the exception? For example something as follows:
try:
do_thing()
except UserAbort:
break
except Exception as e:
print(e)
continue
You could just force to exit the program whenever the exception happens:
import sys
# ...
try:
do_thing()
except UserAbort:
break
except KeyboardInterrupt:
sys.exit()
pass
except Exception as e:
print(e)
continue

nested try except in python

Try:
#some statement
Try:
#some statement
Except:
#statement1
Raise exception()
#statement2
Except: #some statement
Can I pass the control like the above code in python., will the inner except pass the control to the outer except and will the #statement2 be executed?
This code will answer your question:
#!/usr/bin/env python
import sys
try:
try:
raise Exception("first exception")
except Exception as e:
print e.message
raise Exception("second exception")
print "second statement" # never printed - 'dead code'
except Exception as e:
print e.message
Both except blocks are executed but the statement after raising the second exception is not.
Generally you should know that once an exception is raised, nothing executes until it is caught by an except block that is relevant to this exception or any superclass of it.

Categories