Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stop a program when an exception is raised in Python?

I need to stop my program when an exception is raised in Python. How do I implement this?

like image 283
user46646 Avatar asked Jan 13 '09 13:01

user46646


People also ask

How do I stop a program after an exception?

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.

Does raising an exception stop the program?

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.

How do you stop exceptions in Python?

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.

How do you handle a raised exception 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.


2 Answers

import sys  try:   print("stuff") except:   sys.exit(1) # exiing with a non zero value is better for returning from an error 
like image 68
Loïc Wolff Avatar answered Oct 16 '22 04:10

Loïc Wolff


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.

like image 26
Abgan Avatar answered Oct 16 '22 04:10

Abgan