QL REQUIRE

From Quantlib
Jump to: navigation, search

QL_REQUIRE is one of the macros which take care of the error handling. Imagine that you would like to check a double variable against zero before dividing. If the variable is zero, you'd like to throw an exception. A common way to do this would be

if(x==0){
    std::string myError("Divided by Zero");
    throw myError;
}

where a string object is thrown. QuantLib handles the same event with a one-liner:

QL_REQUIRE(x!=0,"Divided by Zero")

The macro requires two inputs. The first one is a boolean variable. The second one is a string, which represents the error message. The macro throws an std::exception object if the given condition is false. The exception can be handled as usual in a catch block. We will demonstrate the functionality via the following function

void testingMacros1 (){
     double x =0.0;
     QL_REQUIRE (x!=0 ," Zero number !");
}

The function is called in a try, catch block as shown in the main function below

int _tmain ( int argc , _TCHAR * argv []){
 
try {
     testingMacros1 ();
} catch ( std :: exception & e) {
     std :: cout << e. what () << std :: endl ;
     return 1;
} catch (...) {
     std :: cout << " unknown error " << std :: endl ;
     return 1;
}
 
}

Executing the main returns

Zero number!

The information content of the error can be extended. For example, one can modify QuantLib such that the function name, the name of the file or the line number is printed. To do this, go to

<ql/userconfig.hpp>

For the function name, change

#ifndef QL_ERROR_FUNCTIONS
// #define QL_ERROR_FUNCTIONS
#endif

to (uncomment the middle line)

#ifndef QL_ERROR_FUNCTIONS
#define QL_ERROR_FUNCTIONS
#endif

The same procedure can be used to show the file and line information by changing the QL_ERROR_LINES block in the same file. You need to recompile QuantLib to see the changes.