Does Raising A Manual Exception In A Python Program Terminate It?
Does invoking a raise statement in python cause the program to exit with traceback or continue the program from next statement? I want to raise an exception but continue with the r
Solution 1:
I want to raise an exception but continue with the remainder program.
There's not much sense in that: the program control either continues through the code, or ripples up the call stack to the nearest try
block.
Instead you can try some of:
- the
traceback
module (for reading or examining the traceback info you see together with exceptions; you can easily get it as text) - the
logging
module (for saving diagnostics during program runtime)
Example:
def somewhere():
print'Oh no! Where am I?'
import tracebackprint''.join(traceback.format_stack()) # ortraceback.print_stack(sys.stdout)
print'Oh, here I am.'
def someplace():
somewhere()
someplace()
Output:
Oh no! Where am I?
File "/home/kos/exc.py", line 10, in <module>
someplace()
File "/home/kos/exc.py", line 8, in someplace
somewhere()
File "/home/kos/exc.py", line 4, in somewhere
print''.join(traceback.format_stack())
Oh, here I am.
Solution 2:
Only an uncaught exception will terminate a program. If you raise an exception that your 3rd-party software is not prepared to catch and handle, the program will terminate. Raising an exception is like a soft abort: you don't know how to handle the error, but you give anyone using your code the opportunity to do so rather than just calling sys.exit()
.
If you are not prepared for the program to exit, don't raise an exception. Just log the error instead.
Post a Comment for "Does Raising A Manual Exception In A Python Program Terminate It?"