Main Menu

search

You are here

Python: Error Handling

[last updated: 2019-11-01]
go to: Python home page
go to: Python: Programming Statements
-----

  • Errors are of several types:
    • FileNotFound
    • 'Type' something or other ...
    • [something] not defined
    • others ...
  • Each error type must be handled/coded separately.
    While there may be other ways of doing it, the 'try' - 'except' structure works:

    try:
         [expressions]
    except [error type]:
         [expressions]

  • However you can capture all error types with:
    ...
    except Exception:
  • If you want to put the error message into a variable, eg. so you can print it, do this:
    ...
    except Exception as errorMsg:
         print(errorMsg)
  • You can also investigate the exception errors using system parameters:
    • sys.exc_info()
      This function returns a tuple of three values that give information about the exception that is currently being handled. If no exception is being handled anywhere on the stack, a tuple containing three None values is returned.
      Otherwise, the values returned are:
        (type, value, traceback).

      Their meaning is:

        'type' gets the exception type of the exception being handled (a class object);
        'value' gets the exception parameter (its associated value or the second argument to raise, which is always a class instance if the exception type is a class object);
        'traceback' gets a traceback object (see the Reference Manual) which encapsulates the call stack at the point where the exception originally occurred.

      If exc_clear() is called, this function will return three None values until either another exception is raised.

.

.

.

eof