1

I wonder if there is a way to capture the exception information when running a Python script, besides using try-except statements?

My Python script is subject to constant change by different people. Errors can occur anywhere inside the file, either a syntax or value error.

I want to be able to interpret the exception information and provide custom error messages to people, for friendly reminding.

I don't want, or couldn't afford, to include all code lines into the try statement. Just wonder if I can have custom error message displayed whenever there is an exception raised.

Thank you for helping out here!

Regards, Paul

2
  • That's pretty tough. Do you run the script directly? Or could you perhaps call it from a different file? What you want is possible In the latter case Commented Jun 1, 2020 at 5:26
  • What would be the alternative to try? Having an application with unhandled exceptions? And BTW if someone supplies code with a SyntaxError he has never run it and your development process are not what they should be. Commented Jun 1, 2020 at 5:34

1 Answer 1

2

The beauty of a try/catch statement is that it catches any unhandled exceptions raised by any lower scope. You can put a try/catch at the very top level of your script and it'll catch anything that happens anywhere else. There's no need to wrap each line individually!

if __name__ == '__main__':
    try:
        my_main_func()
    except Exception as e:
        # this will catch any exception from anywhere else in the program!
        print(e)
        raise
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.