-2

I have written a program that needs to quit if it encounters a certain event.

I can raise exceptions, but how do I raise a fatal exception that ends the program?

cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • 3
    you could call `sys.exit()`, if program does not trap `BaseException` it'll work. – Jean-François Fabre Jan 23 '17 at 15:11
  • 1
    https://stackoverflow.com/questions/27995057/why-is-it-recommended-to-derive-from-exception-instead-of-baseexception-class-in – Josh Lee Jan 23 '17 at 15:13
  • like @Jean-FrançoisFabre said, you could use exit, but why would you want to do that? Your python module doesn't know what process is using it and whether it should force it to stop or not. You should raise an exception and let the function above decide what to do – Dunno Jan 23 '17 at 15:14
  • @Dunno: `sys.exit` raises `SystemExit` exception. – Jean-François Fabre Jan 23 '17 at 15:15

1 Answers1

1

Exceptions are a part of the program flow. They are not intended to end a program, but to indicate an error going realtime and let the program handle it.

Use sys.exit() to end programs during runtime.

Uriel
  • 15,579
  • 6
  • 25
  • 46