I need to stop my program when an exception is raised in Python. How do I implement this?
If you let the exception propagate all the way up to the main() method, the program will end. There's no need to call System. exit , just allow the exception to bubble up the stack naturally (by adding throws IOException ) to the necessary methods.
When an exception is raised, no further statements in the current block of code are executed. Unless the exception is handled (described below), the interpreter will return directly to the interactive read-eval-print loop, or terminate entirely if Python was started with a file argument.
Use the pass Statement in the except Block in Python When the pass statement is used in the try... except statements, it simply passes any errors and does not alter the flow of the Python program. The following code uses the pass statement in the except block to ignore an exception and proceed with the code in Python.
In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.
import sys try: print("stuff") except: sys.exit(1) # exiing with a non zero value is better for returning from an error
You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise:
try: doSomeEvilThing() except Exception, e: handleException(e) raise
Note that typing raise
without passing an exception object causes the original traceback to be preserved. Typically it is much better than raise e
.
Of course - you can also explicitly call
import sys sys.exit(exitCodeYouFindAppropriate)
This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With