Next: Values From Inferior, Previous: Threading in GDB, Up: Python API [Contents][Index]

#### 23.3.2.3 Exception Handling

When executing the `python` command, Python exceptions uncaught within the Python code are translated to calls to GDB error-reporting mechanism. If the command that called `python` does not handle the error, GDB will terminate it and print an error message. Exactly what will be printed depends on `set python print-stack` (see Python Commands). Example:

    (gdb) python print foo
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
    NameError: name 'foo' is not defined

GDB errors that happen in GDB commands invoked by Python code are converted to Python exceptions. The type of the Python exception depends on the error.

`gdb.error` ¶

  This is the base class for most exceptions generated by GDB. It is derived from `RuntimeError`, for compatibility with earlier versions of GDB.

  If an error occurring in GDB does not fit into some more specific category, then the generated exception will have this type.

`gdb.MemoryError` ¶

  This is a subclass of `gdb.error` which is thrown when an operation tried to access invalid memory in the inferior.

`KeyboardInterrupt` ¶

  User interrupt (via `C-c` or by typing `q` at a pagination prompt) is translated to a Python `KeyboardInterrupt` exception.

In all cases, your exception handler will see the GDB error message as its value and the Python call stack backtrace at the Python statement closest to where the GDB error occurred as the traceback.

When implementing GDB commands in Python via `gdb.Command`, or functions via `gdb.Function`, it is useful to be able to throw an exception that doesn’t cause a traceback to be printed. For example, the user may have invoked the command incorrectly. GDB provides a special exception class that can be used for this purpose.

`gdb.GdbError` ¶

  When thrown from a command or function, this exception will cause the command or function to fail, but the Python stack will not be displayed. GDB does not throw this exception itself, but rather recognizes it when thrown from user Python code. Example:

      (gdb) python
      >class HelloWorld (gdb.Command):
      >  """Greet the whole world."""
      >  def __init__ (self):
      >    super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_USER)
      >  def invoke (self, args, from_tty):
      >    argv = gdb.string_to_argv (args)
      >    if len (argv) != 0:
      >      raise gdb.GdbError ("hello-world takes no arguments")
      >    print ("Hello, World!")
      >HelloWorld ()
      >end
      (gdb) hello-world 42
      hello-world takes no arguments

Next: Values From Inferior, Previous: Threading in GDB, Up: Python API [Contents][Index]