Next: , Previous: Basic Python, Up: Python API



23.2.2.2 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 containing the Python exception name, the associated value, and the Python call stack backtrace at the point where the exception was raised. 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 RuntimeError exceptions. User interrupt (via C-c or by typing q at a pagination prompt) is translated to a Python KeyboardInterrupt exception. If you catch these exceptions in your Python code, your exception handler will see RuntimeError or KeyboardInterrupt as the exception type, the gdb error message as its value, and the Python call stack backtrace at the Python statement closest to where the gdb error occured as the traceback.

When implementing gdb commands in Python via gdb.Command, 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. Use the gdb.GdbError exception to handle this case. Example:

     (gdb) python
     >class HelloWorld (gdb.Command):
     >  """Greet the whole world."""
     >  def __init__ (self):
     >    super (HelloWorld, self).__init__ ("hello-world", gdb.COMMAND_OBSCURE)
     >  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