How to catch the runtime error

We talked about how to find the runtime error in a previous post (Finding the runtime error in your C++ code). Many times, we could figure out what the error is by checking the code closely once figure out which part of the code is causing the problem. Here is another method that could give us some extra help on how to figure out the issue. That is - to catch the runtime error! :smiley:

All you need to do is to put your C++ code within the bracket of try { } and add some catch code to catch the error. The following are the details:

try {
	// Your C++ code
} catch(GRBException e) {
	cout << "Error code = " << e.getErrorCode() << endl;
	cout << e.getMessage() << endl;
} catch (...) {
	cout << "Error during optimization" << endl;
}

However, please make sure this part of the code should be put after int main { and before return 0;, like the following:

#include "gurobi_c++.h"
#include<iostream>
int main()
{
	try {
		// Your C++ code
	} catch(GRBException e) {
		cout << "Error code = " << e.getErrorCode() << endl;
		cout << e.getMessage() << endl;
	} catch (...) {
		cout << "Error during optimization" << endl;
	}
	return 0;
}

This way, if your code has a runtime error, it will be displayed in the command window.

Before you add try and catch, if there is a runtime error, something the following will be displayed:

terminate called after throwing an instance of ‘GRBException’
Aborted (core dumped)

After you add try and catch, if there is a runtime error, something the following will be displayed:

Error code = 10005
Constr::get

With the error code, you could have a better guess on what is causing the runtime error.

You could look up the Gurobi error code at https://www.gurobi.com/documentation/9.0/refman/error_codes.html

In my case, the error code was 10005, which means I was trying to access something that was not accessible. The Constr::get showed that the error happened when I was trying to access a constraint. In fact, this error happened when I was trying to get the dual values in the mixed-integer linear program (MILP), however, Gurobi only support getting dual values when the optimization problem is continuous (Details: How to get the dual value of a constraint using C++&Gurobi?).