diff --git a/ortools/linear_solver/gurobi_interface.cc b/ortools/linear_solver/gurobi_interface.cc index 54bdc34ace..94291cc707 100644 --- a/ortools/linear_solver/gurobi_interface.cc +++ b/ortools/linear_solver/gurobi_interface.cc @@ -21,6 +21,7 @@ #include #include #include +#include #include "ortools/base/commandlineflags.h" #include "ortools/base/integral_types.h" @@ -176,10 +177,13 @@ class GurobiInterface : public MPSolverInterface { // Creates a LP/MIP instance with the specified name and minimization objective. GurobiInterface::GurobiInterface(MPSolver* const solver, bool mip) : MPSolverInterface(solver), model_(nullptr), env_(nullptr), mip_(mip) { - if (GRBloadenv(&env_, nullptr) != 0 || env_ == nullptr) { - LOG(FATAL) << "Error: could not create environment: " - << GRBgeterrormsg(env_); - } + + int ret = GRBloadenv(&env_, nullptr); + if (ret != 0 || env_ == nullptr) { + std::string err_msg = GRBgeterrormsg(env_); + LOG(DFATAL) << "Error: could not create environment: " << err_msg; + throw std::runtime_error(std::to_string(ret) + ", " + err_msg); + } CheckedGurobiCall(GRBnewmodel(env_, &model_, solver_->name_.c_str(), 0, // numvars diff --git a/ortools/linear_solver/python/linear_solver.i b/ortools/linear_solver/python/linear_solver.i index e5c24fcf5b..32b618173b 100644 --- a/ortools/linear_solver/python/linear_solver.i +++ b/ortools/linear_solver/python/linear_solver.i @@ -73,6 +73,17 @@ from ortools.linear_solver.linear_solver_natural_api import VariableExpr } // %pythoncode } +// Catch runtime exceptions in class methods +%extend MPSolver { + %exception MPSolver { + try { + $action + } catch ( std::runtime_error& e ) { + SWIG_exception(SWIG_RuntimeError, e.what()); + } + } +} + %extend MPSolver { // Change a (bool, std::string*) outputs to a python std::string (empty if bool=false). std::string ExportModelAsLpFormat(bool obfuscated) {