Exit without errors

Sometimes to terminate a code block, and it’s related process, we raise errors. These errors can be handled on the calling function side. Here, we have raised a SyntaxError with custom error message to terminal the code. The try…except block handles the error and terminates the code normally.

Using explicitly raised errors to terminate a process

In the given example, the `main` function intentionally raises a custom `SyntaxError`. The `try-except` block in the `__main__` section catches the specific `SyntaxError` raised by the `main` function, and prints “We caught the error!” as a response.

Python3




def main():
    raise SyntaxError("Custom Syntax Error")
 
if __name__ == "__main__":
    try:
        main()
    except SyntaxError:
        print("We caught the error!")


Output:

We caught the error!

How to Exit a Python script?

In this article, we are going to see How to Exit Python Script.

Exiting a Python script refers to the termination of an active Python process. In this article, we will take a look at exiting a Python program, performing a task before exiting the program, and exiting the program while displaying a custom (error) message.

Similar Reads

Exiting a Python Application

There exist several ways of exiting Python script applications, and the following article provides detailed explanations of several such approaches How to exit Python script....

Detecting Script Exit in Python

...

Exit without errors

Sometimes it is required to perform certain tasks before the exit python script. For that, it is required to detect when the script is about to exit. atexit is a module that is used for performing this very task. The module is used for defining functions to register and unregister cleanup functions. Cleanup functions are called after the code has been executed. The default cleanup functions are used for cleaning residue created by the code execution, but we would be using it to execute our custom code....

Exit with Error Messages

...