Print a custom error message and gracefully exit

How can I print a custom error message and gracefully exit the Python script at the same time?

You catch the error in whatever way you want to do that, then exit("This is the message you want to display")

How you choose to catch said error, would depend on what error you’re expecting to catch.

1 Like

When you raise an exception, it will print the message you pass into the exception.

            raise ReplacementValueAtPurchaseDateError(
                "Cannot have replacement value at purchase date")

This will print “Cannot have replacement value at purchase date” for the user.

Beyond that, it will also provide a lot of information in the traceback about where the error occurred.

If you mean exiting without relying on the exception, @rob42 has the solution. However, in lots of situations letting an exception be processed would be more gracefully. E.g. when you create a new file in your program, the file will be deleted after failure and restart will be a lot easier.

1 Like