Unidata / netcdf-cxx4

Official GitHub repository for netCDF-C++ libraries and utilities.
Other
124 stars 49 forks source link

Exception handling with NcException #40

Open Gronnesby opened 7 years ago

Gronnesby commented 7 years ago

Hi, I'm pretty new to C++, so please let me know if I've got this wrong.

In the example files the catch-all exception handling looks something like this:


try
   {
        /* Code that might throw an exception */
   }
   catch(NcException& e) // Catch-all exceptions
     {
       e.what(); // Will this print exception information? It should return a const char *, right?
       cout<<"FAILURE*************************************"<<endl;
       return NC_ERR;
     }

What I am wondering about is how do you actually get any useful information out of the exception handling? I've tried to read a NcFile into a map like so:


try
{
    NcFile datafile(filename, NcFile::read);
    NcVar data = datafile.getVar("data");

    map<string, NcVarAtt> m = data.getAtts();

    if (data.isNull())
        cout << "Data is null" << endl;
}
catch (NcException& e)
{
    // Neither e.what() or string(e.what()) prints anything useful
    cerr << "An exception occured while reading a file: " << e.what() << endl;
}

Which essentially prints garbage values:

An exception occured while reading a file: p�

If I remove the whole try-catch block and just don't handle the exception, i get this:

terminate called after throwing an instance of 'netCDF::exceptions::NcBadId'
  what():  
Aborted (core dumped)

Any idea why the e.what() function only returns garbage values (the "p" seems to always crop up)? As per the documentation for std::exception::what it should return a const char *. Or have i completely misunderstood exception handling in C++?

WardF commented 7 years ago

It appears that the e.what() is not being properly populated, hence an empty string is being printed. The exception refers to having an incorrect ncid value reported. This code was donated to Unidata, let me dig in and take a look to see if I can fix this up.