Re: How to call TPyException in Python?

From: <wlavrijsen_at_lbl.gov>
Date: Tue, 3 May 2011 22:51:31 -0700


Akira,

> What I want to do is to throw C++ exceptions from my C++ ROOT code, and
> catch them in PyROOT.

that's fine, just throw any old exception, but preferably ones derived from std::exception b/c their what() can be called to transfer the error message. All C++ exceptions are turned into instances of Exception and can be caught.

For example:

% cat dothrow.C
#include <stdexcept>

void dothrow() {

    throw std::runtime_error( "hey there!" ); }

% python
>>> import ROOT
>>> ROOT.gROOT.LoadMacro( 'dothrow.C+' ) Info in <TUnixSystem::ACLiC>: creating shared library /Users/wlav/./dothrow_C.so 0
>>> try:

...    ROOT.dothrow()
... except Exception, e:
...    error = e
... 

>>> print error
hey there! (C++ exception)
>>> ^D

Perhaps the translation should be finer grained (e.g. std::runtime_error could have been RuntimeError), but no-one's ever asked for that. :)

> ==============
> http://root.cern.ch/root/html/PyROOT__TPyException.html
> Purpose: A C++ exception class for throwing python exceptions
> through C++ code.
> ==============

The important bit is "through", rather than "from." TPyException is used to get _python_ exceptions through C++ back into python. For example, if a python callable is handed to a TF1 for plotting on a canvas, and the callable then raises. That raised exception (python) is turned into a thrown TPyException (C++), caught, and turned back into a python exception (which is no work, really, since it's already set, but the return value is what matters).

> Is there any tutorial of TPyException?

No: there's only one use that I'm aware of and that's deep inside PyROOT.

Best regards,

            Wim

-- 
WLavrijsen_at_lbl.gov    --    +1 (510) 486 6411    --    www.lavrijsen.net
Received on Wed May 04 2011 - 07:51:45 CEST

This archive was generated by hypermail 2.2.0 : Wed May 04 2011 - 23:50:01 CEST