Search code examples
pythonerror-handlingcustomization

How to Create Custom Error Messages in Python


How would I go about creating custom error messages in python without wrapping each statement in a try-except clause? For instance (assuming python3.6), assume I enter the following code in the python prompt:

the_variable=5
print(the_varible)

This will return:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'the_varible' is not defined

Say I wanted to return an custom exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'the_varible' is not defined. Did you mean 'the_variable'?

Of course, this an extremely contrived example, I could easily wrap this particular example in a try: except clause (e.g. like here, here and many others), but what I more generally want is to customize any error message of all statements in the program

For instance, if I create a file called my_script.py, which contains:

the_variable=5
print(the_varible)

and I run it with python my_script.py. I want to receive the same custom error message as above.


Solution

  • You could catch all errors in your main() function, which is conventionally the starting function of an application.

    def main():
        try:
            // all the rest of your code goes here
        except NameError as err:
            // your custom error handling goes here
        // other custom error handlers can go here