Skip to content

pybind breaks exception handling #1272

Closed
@wichert

Description

@wichert

I've spent many hours today trying to figure out why my exception handling does not work. I have a C++ library which raises an exception in its own namespace: stylist::unsuitable_error. Catching this error works perfectly within that library. In my wrapper code it fails. The exception is defined like this:

class unsuitable_error : public std::logic_error {
public:
	explicit unsuitable_error(const std::string& __arg) : std::logic_error(__arg), reasons(), causes() { }
	virtual ~unsuitable_error() throw() { }

	std::list<const char*> reasons;
	struct cause_type { … };
	std::list<cause_type> causes;
};

I have some code which tries to handle that exception being thrown:

	AdviceWrapper* doit(const Article& article, const Body& body) {
		auto result = new AdviceWrapper();

		try {
			result->advise = advise(article, body);
			cerr << "All OK" << endl;
		} catch (const unsuitable_error &e) {
			cerr << "Not suitable" << endl;
		} catch (...) {
			cerr << "Bad exception" << endl;
		}
		return result;
	}

void GO() {
  article = … ;
  body = … ;
  doit(article, body);
}

This works perfectly in a standalone program:

$ cat src/standalone.cc 
void GO();

int main() {
	GO();
	return 0;
}
$ ./standalone 
Not suitable

However, the exact same code in pybind11 breaks. The wrapper code is simple enough:

#include <pybind11/pybind11.h>

namespace py = pybind11;


void GO();

PYBIND11_MODULE(_stylist, m) {
	m.doc() = "CurveTips stylist";

	m.def("GO", GO);
}

and running that results in:

$ python3 -c 'import _stylist ; _stylist.GO()'
Bad exception

The standalone tool and Python wrapper are compiled from the same CMake config:

project(_stylist)
cmake_minimum_required(VERSION 2.8.12)

set(PACKAGE stylist)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(Boost_USE_MULTITHREADED ON)

find_package(Stylist REQUIRED)
include_directories(SYSTEM ${Stylist_INCLUDE_DIRS})
link_directories(${Stylist_LIBRARY_DIRS})

add_subdirectory(pybind11)
pybind11_add_module(_stylist SHARED src/stylist.cc src/tst.cc)
target_link_libraries(_stylist PRIVATE ${Stylist_LIBRARIES})

add_executable(standalone src/standalone.cc src/tst.cc)
target_link_libraries(standalone PRIVATE ${Stylist_LIBRARIES})

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions