There is an executable file and I am throwing an exception at the very beginning of the solution in program.cs. When loading this executable file from a different solution using CreateProcessA(), I see that the process loads and does not give me an error message. Any idea on how to catch this exception?
STARTUPINFOA startupInfo;
PROCESS_INFORMATION pi;
ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
ZeroMemory(&pi, sizeof(pi));
const auto dwCreationFlags = showConsole ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW;
auto canCreate = true;
if (!CreateProcessA(
nullptr, // LPCWSTR IpApplicationName
const_cast<LPSTR>(command.c_str()), // LPSTR IpCommandLine
nullptr, // LPSECURITY_ATTRIBUTES IpProcessAttributes
nullptr, // LPSECURITY_ATTRIBUTES IpThreadAttributes
false, // BOOL bInheritHandles,
dwCreationFlags, // DWORD dwCreationFlags
nullptr, // LPVOID IpEnvironment
nullptr, // LPCWSTR IpCurrentDirectory
&startupInfo, // LPSTARTUPINFOW IpStartupInfo
&pi // LPPROCESS_INFORMATION IpProcessInformation
))
{
canCreate = false;
return Status(WinUtil::GetLastErrorMessage());
}
//canCreate = false;
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, 0);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return Status();
I am expecting it to return false and catch the exception.
However, it currently loops for a while, and then throws out a generic message saying that it failed to start. It's not catching the exception I threw at the very beginning of the solution.
You can't throw exceptions across language boundaries, let alone process boundaries. A C++ app cannot catch an exception thrown in a separate C# app.
When the C# app throws an exception that is not caught, it will simply terminate itself. The C++ app that launched it cannot catch that uncaught exception. The only thing it can do is wait for the C# app to terminate (which you are already doing), and then use
GetExitCodeProcess()to get the exit code, which will be non-zero on an unexpected failure (such as0xE0434352for an uncaught managed exception,0xC0000005for an access violation,0xC00000FDfor a stack overflow, etc).See: Exit Code When Unhandled Exception Terminates Execution?