Search code examples
c++exceptiontry-catchunhandled-exceptionmsxml

Exception isn't handled while occuring in a try block in C++


I have the following code :

#import <msxml6.dll>
using namespace MSXML2;

... 

IXMLDOMSchemaCollectionPtr   pXS;
IXMLDOMDocument2Ptr          pXD = NULL;
MSXML2::IXMLDOMParseErrorPtr         pErr = NULL;
_bstr_t                      strResult = "";

HRESULT hr = pXS.CreateInstance(__uuidof(XMLSchemaCache60));

CComVariant  xsd_file;
_bstr_t bstrXSD(L"test_xsd.xsd");

BSTR empty_bstr = SysAllocString(L"urn:namespace");

try {
    hr = pXS->add(_bstr_t(""), bstrXSD);
}
catch (const std::exception& e) {
    std::cerr << "Error: " << e.what() << std::endl;
}

I have an exception unhandled when I run this, it happens on this line hr = pXS->add(_bstr_t(""), bstrXSD);. I don't understand how an exception can be unhandled while being thrown inside a try block.

Here's the stack trace:

FacturX_proto.exe!_com_raise_error(HRESULT hr, IErrorInfo * perrinfo) Line 19   C++
FacturX_proto.exe!_com_issue_error(HRESULT hr) Line 40
FacturX_proto.exe!_com_ptr_t<_com_IIID<MSXML2::IXMLDOMSchemaCollection,&_GUID_373984c8_b845_449b_91e7_45ac83036ade>>::operator->() Line 310 C++

I'd like to know why is an exception being thrown there, but to know that I need to know first why is this exception not handled by this try/catch block.

I am not an expert in C++ so there might be something I don't understand. I've searched for solutions but I couldn't find any.


Solution

  • Catching all exceptions in C++ is done with catch(...), not catch(const std::exception& e). There is no requirement whatsoever that types of exceptions are related to std::exception. Any class or scalar type can be thrown. Deriving exception types from std::exception is just a pattern that the C++ standard library itself follows.

    Of course, then you don't know what the type of the exception is in the handler and you can't access it as you are trying in e.g. e.what().

    Instead have a look at the documentation of the function you are calling and what types of exceptions it is supposed to throw, and then write specific handlers for these types and use the interface provided by the specific exception type.