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.
Contact Us