Use the sys.exit:

import sys

try:
    # do something
except Exception, e:
    print >> sys.stderr, "does not exist"
    print >> sys.stderr, "Exception: %s" % str(e)
    sys.exit(1)

A good practice is to print the Exception that occured so you can debug afterwards.

You can also print the stacktrace with the traceback module.

Note that the int you return in sys.exit will be the return code of your program. To see what exit code your program returned (which will give you information about what happens and can be automated), you can do:

echo $?
Answer from Charles Menguy on Stack Overflow
🌐
Python Basics
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
This prevents abrupt exits of the program on error. In the example below we purposely raise an exception. ... After the except block, the program continues. Without a try-except block, the last line wouldn't be reached as the program would crash. $ python3 example.py Divided by zero Should ...
Discussions

Try/Except issue with exiting program on error : Forums : PythonAnywhere
Hi, I am new (actually very new) to using Python and I am trying to figure out how to stop code from running and printing error message if there is an error using try/except. I thought I could add quit() or sys.exit(1) , but both of those are not recognized and come back with an error code ... More on pythonanywhere.com
🌐 pythonanywhere.com
January 31, 2018
quit() in while loop not wokring with try-except block
quit works by raising the SystemExit exception, which normally shuts down the script. But you're catching every exception in your except clause. Don't do that. Be specific about the exception types you want to catch. More on reddit.com
🌐 r/learnpython
9
20
May 11, 2022
Python won't spit out sys.exit message in try function
I'm currently playing around with ... course 'Python for beginners' into my own hands. I am using the Try/except function at the beginning of the code as I want to prevent the user from actually buying more tickets than what's available. Everything is working excellent except for one of the sys.exit() ... More on teamtreehouse.com
🌐 teamtreehouse.com
2
March 31, 2020
How do I exit a program in a try/except block in Python through a function? - Stack Overflow
I am making the game Wordle in Python and I am nearing the end. Now, I am trying to end the program whenever the user guesses the word right but whatever I am trying, nothing is working. I tried do... More on stackoverflow.com
🌐 stackoverflow.com
People also ask

What is try/except in Python?
try/except handles exceptions (errors) so your program does not crash unexpectedly.
🌐
pythonbasics.org
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
How do you catch a specific exception?
except ValueError: catches only ValueError exceptions.
🌐
pythonbasics.org
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
What is the finally clause?
Code in finally always runs whether or not an exception occurred.
🌐
pythonbasics.org
pythonbasics.org › home › python basics › try and except in python
Try and Except in Python - pythonbasics.org
🌐
W3Schools
w3schools.com › python › python_try_except.asp
Python Try Except
The finally block lets you execute code, regardless of the result of the try- and except blocks. ... When an error occurs, or exception as we call it, Python will normally stop and generate an error message.
🌐
Iditect
iditect.com › faq › python › how-to-exit-program-in-tryexcept-in-python.html
How to exit program in try/except in python?
In Python, you can exit a program gracefully from within a try/except block using the sys.exit() function or by raising a custom exception.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-try-except
Python Try Except - GeeksforGeeks
June 8, 2026 - Errors and exceptions can interrupt the normal flow of a program during execution. Python provides try and except blocks to handle such errors gracefully without stopping the entire program.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Try, except, else, finally in Python (Exception handling) | note.nkmk.me
August 15, 2023 - Built-in Exceptions - Exception hierarchy — Python 3.11.3 documentation · BaseException ├── BaseExceptionGroup ├── GeneratorExit ├── KeyboardInterrupt ├── SystemExit └── Exception ├── StopAsyncIteration ├── StopIteration ├── ... ... Since SystemExit and KeyboardInterrupt do not inherit from Exception, using Exception in the except clause will not catch sys.exit() or interrupts like Ctrl + C.
Find elsewhere
🌐
Python Forum
python-forum.io › thread-2277.html
How to exit after a try exception?
March 4, 2017 - I've read so much about try and exception but none tell how to exit the program gracefully and not continue the rest of the code. For example: try: result = x / y except ZeroDivisionError: print "divi
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter10.03-Try-Except.html
Try/Except — Python Numerical Methods
Then if the exception type matches the exception named after the except keyword (ExceptionName), the code in the except statement will be executed (code block 2). If nothing in this block stops the program, it will continue to execute the rest of the code outside of the try-except code blocks.
🌐
PythonAnywhere
pythonanywhere.com › forums › topic › 12385
Try/Except issue with exiting program on error : Forums : PythonAnywhere
January 31, 2018 - giles | 12902 posts | PythonAnywhere staff | Feb. 1, 2018, 12:56 p.m. | permalink ... Here is the error message I get when I enter a string value for hours: (this occurred with import sys at top of code and sys.exit(1) at the end of the except line of code... Error, please enter numeric value Traceback (most recent call last): File "/home/rockmono/PY4E 4_6.py", line 11, in <module> h = float(hrs) ValueError: could not convert string to float: 'ten' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/rockmono/PY4E 4_6.py", line 15, in <module> sys.exit(1)
Top answer
1 of 2
1
I wouldn't use a try block there. There is no error for it to fail on. You could use a a try block to stop them from entering letters or for a divide by 0. I would just use an else like this: ```python import sys import math price in $ TICKET_PRICE = 10 tickets_remaining = 100 Asking for username through input and assigning it to a new variable name = input("Hello! What is your name? ") Saying hello to the user, including name, making it more personal print("Welcome to the page, {}. There are currently {} tickets remaining.".format(name, tickets_remaining)) Using the try/except function here as I want to prevent users from buying more than what's actually in stock. If the user exceeds the ticket_remaining they will be thrown out, else, continue try: quantity = int(input("How many tickets would you like to buy? ")) if quantity > ticketsremaining: sys.exit("Woah! Slow down there, Cowboy! You're trying to buy too many tickets. We only have {} ticket(s) left.".format(ticketsremaining)) else: #except: subtotal = math.ceil(quantity * TICKET_PRICE) answer = input("The subtotal is gonna be ${}, would you like to continue? (yes/no) ".format(subtotal)) if answer == 'yes': sys.exit(("Sold to the buyer {} for ${}! Thanks for the purchase, {}, we hope that you enjoy the show.".format(name, subtotal, name))) else: sys.exit("Okay, then.") ``` I think it also asks to make a loop to buy multiple tickets. Hopefully you will give that a try too. Good luck and keep at it!
2 of 2
0
I'm not sure how you were seeing that final message. According to the documentation: The sys.exit() function allows the developer to exit from Python. The exit function takes an optional argument, typically an integer, that gives an exit status. Zero is considered a “successful termination”.
🌐
Python documentation
docs.python.org › 3 › tutorial › errors.html
8. Errors and Exceptions — Python 3.14.7 documentation
Exception handlers do not handle only exceptions that occur immediately in the try clause, but also those that occur inside functions that are called (even indirectly) in the try clause.
🌐
Reddit
reddit.com › r/learnpython › try/except - does not exit gracefully. program continues to next block
r/learnpython on Reddit: Try/except - does not exit gracefully. Program continues to next block
July 19, 2015 -

I don't understand why the try/except in this sample, will not exit gracefully, and instead continues to try to calculate the rate.
I thought the try/except caused a program to exit, if the except gets executed:

hours = raw_input("how long worked: ")
rate = raw_input("pay rate: ")
try: 
    hours = float(hours)
    rate = float(rate)
except:
    print "[+] Error -- Please enter numeric input "

if hours > 40:
    rate *= 1.5

total = hours * rate
print "you made %s dollars" % total  

This is the error I receive:

c:\home\dev\tutorial>python payrate.py
how long worked: five
pay rate: 4
[+] Error -- Please enter numeric input
Traceback (most recent call last):
  File "payrate.py", line 10, in <module>
    rate *= 1.5
TypeError: can't multiply sequence by non-int of type 'float'

Cheers.

🌐
Python Land
python.land › home › language deep dives › python try except: examples and best practices
Python Try Except: Examples And Best Practices • Python Land Tutorial
January 29, 2026 - It can be in function C (closest to the exception), in function B (somewhat farther), in function A, or even at the top level of the program where we called function A. If Python finds a suitable except block, it executes the code in that block. If it doesn’t find one, Python handles the exception by itself. This means it will print the exception and exit the program since it has no clue what to do with it.
🌐
Learnpython
practical.learnpython.dev › 06_object_oriented_python › 50_exceptions
Exceptions :: Practical Python: A One Day Python Immersion Course by Nina Zakharenko
sys.exit() generates a SystemExit exception, which inherits from the master BaseException class, which makes it possible for clean-up handlers (such as finally statements) to run. Many languages have the concept of the “Try-Catch” block. Python uses four keywords: try, except, else, and finally.
🌐
GeeksforGeeks
geeksforgeeks.org › python › try-except-else-and-finally-in-python
Try, Except, else and Finally in Python - GeeksforGeeks
Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after normal termination of try block or after try block terminates due to some exception.
Published: July 15, 2025
🌐
Replit
replit.com › home › discover › how to end a program in python
How to end a program in Python | Replit
April 14, 2026 - The fix is to replace os._exit() with sys.exit(). Unlike the abrupt os._exit(), sys.exit() initiates a normal shutdown, allowing any functions registered with atexit to run. This ensures your cleanup tasks—like closing files or database connections—are always executed before the program stops. It's the right choice whenever you need a clean exit that respects your registered handlers, guaranteeing that no important final steps are skipped. A common mistake is using a try...except block that accidentally catches the SystemExit exception raised by sys.exit().
🌐
Pythonread
pythonread.github.io › try-except.html
Try and Except in Python - Python Tutorial
This prevents abrupt exits of the program on error. In the example below we purposely raise an exception. After the except block, the program continues. Without a try-except block, the last line wouldn't be reached as the program would crash. $ python3 example.py Divided by zero Should reach here
🌐
Note.nkmk.me
note.nkmk.me › home › python
How to Exit a Python Program: sys.exit() | note.nkmk.me
April 27, 2025 - Try, except, else, finally in Python (Exception handling) To exit the Python REPL (interactive mode), you can use the built-in functions exit() and quit().