91

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

cHao
  • 84,970
  • 20
  • 145
  • 172
user46646
  • 153,461
  • 44
  • 78
  • 84
  • How do you want your program to stop? – PEZ Jan 13 '09 at 13:23
  • 1
    @Gortok: Thanks for adding [plzsendthecodez] tag. That made my day! – S.Lott Jan 13 '09 at 13:40
  • 1
    If we were in C++ land, I would think that you're looking for the equivalent of "catch throw" in GDB. How ever, in Python the exception carries a backtrace telling you exactly where it's thrown from. Is this not enough? –  Jan 13 '09 at 15:03

5 Answers5

88
import sys

try:
  print("stuff")
except:
  sys.exit(1) # exiting with a non zero value is better for returning from an error
brian d foy
  • 129,424
  • 31
  • 207
  • 592
Loïc Wolff
  • 3,205
  • 25
  • 26
  • 29
    sys.exit(1) would be more appropriate. – Deestan Jan 13 '09 at 14:30
  • 1
    @bruno desthuilliers Well, it's pretty obvious. All he asks was the script exiting when an exception occurs. – Loïc Wolff Jan 13 '09 at 22:20
  • 4
    @Deestan - Why is `sys.exit(1)` more appropriate..? – kramer65 Jul 10 '14 at 20:22
  • 14
    @kramer65: A program exit code of `0` means "finished without errors". Since the `sys.exit` call appears to be caused by an error, it should yield a program exit code that is not `0`. `1` is just a suggestion. – Deestan Aug 11 '14 at 11:28
  • 2
    @LoïcWolff: There's nothing to do for the script to exit when an unhandled exception occurs. That's just the default behaviour - and at least it's a much saner behaviour since 1/ it prints a useful error message including the full traceback and 2/ returns with the appropriate (non zero) exit code. – bruno desthuilliers Oct 08 '14 at 09:24
68

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.

Jaroslav Bezděk
  • 6,967
  • 6
  • 29
  • 46
Abgan
  • 3,696
  • 22
  • 31
  • 1
    As mentioned in [this answer](http://stackoverflow.com/a/18188660/321973) you can however use `sys.exc_info()` to obtain enough information for a preserved re-`raise` if some processing is required – Tobias Kienzler Nov 12 '14 at 14:50
24

If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.

Tobias Kienzler
  • 25,759
  • 22
  • 127
  • 221
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • 9
    This is the only real answer to the unspecific question. All other answers seems to make some implicit assumptions about that the author meant. Since we are talking Python, we should keep it as explicit as possible – tbrlpld Apr 27 '20 at 17:58
10
import sys

try:
    import feedparser
except:
    print "Error: Cannot import feedparser.\n" 
    sys.exit(1)

Here we're exiting with a status code of 1. It is usually also helpful to output an error message, write to a log, and clean up.

Pranab
  • 2,207
  • 5
  • 30
  • 50
  • 10
    an unhandled exception WILL output with a (much more useful) error message (and the full traceback too) AND exit with non-zero status. Your above code snippet is an anti-pattern. – bruno desthuilliers Oct 08 '14 at 09:19
  • It really depends on what the exception is being raised for. Remember that the higher level pattern is EAFP. So it's entirely possible that exception handling is being used to generate user feedback, and that user may only care about a sane error message and could do better without a trace. You can use `logging.exception` to write the traceback to the log, present the user with meaningful feedback and then bail without reraising the exception. – cowbert Jun 29 '19 at 00:17
5

As far as I know, if an exception is not caught by your script, it will be interrupted.

Keltia
  • 14,535
  • 3
  • 29
  • 30