throw .net-wrappable exception from native COM-Dll - exception

In a native-C++-Dll (MFC): how to throw an Exception (with some additional text) that can be catched and handled from a .NET-Client?
This is the native-MFC-Dll which wants to throw an Exception:
void RGaugeTVDDataReader::LoadDataFromFile_HandleException(const CString& szPath) const
{
CString sMessage;
sMessage.Format(_T("TVD-File %s"), static_cast<LPCTSTR>(szPath));
/*1*/ AfxThrowFileException(CFileException::genericException, -1, static_cast<LPCTSTR>(sMessage));
/*2*/ throw std::runtime_error(CT2A(sMessage));
}
The Caller is a .Net-Dll which uses the native dll via a .net-generated-COM-Wrapper.
Both variants (/1/ and /2/) fall into the catch-Block of the .Net-Component but what I get here is just a ´System.Runtime.InteropServices.SEHException´ and the exceptionmessage says "External component has thrown an exception.". Included ErrorCode and HResult is 0x80004005. There is no inner exception, nothing to find about my given text and the stacktrace only contains the managed part.
So the question is: how to throw an excpetion from the native-c++-dll so that a .net-client using it via COM can at least see the message-string?
Alternative question: how to catch and handle the thrown exception in .net correctly?
regards

Related

C++Winrt how to throw and handle exception without terminating program

I have following code
IAsyncOperation<bool> trythiswork()
{
bool contentFound{ false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result)
if (result)
{
contentFound = true;
}
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
When the result is false, it fails and throws but catch goes to fail fast and program terminates. How does log function terminate the program? Isn't it supposed to only log the exception? I assumed that I am handling this exception so program won't crash but it is crashing.
So how to throw and catch so that program does not terminate? I do want to throw. And also catch and preferably log the exception as well.
Thanks
The issue can be reproduced using the following code:
IAsyncOperation<bool> someAsyncFunc() { co_return false; }
IAsyncOperation<bool> trythiswork()
{
auto contentFound { false };
try
{
auto result = co_await someAsyncFunc();
winrt::check_bool(result);
// throw std::bad_alloc {};
contentFound = true;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
}
co_return contentFound;
}
int main()
{
init_apartment();
auto result = trythiswork().get();
}
As it turns out, everything works as advertised, even if not as intended. When running the code with a debugger attached you will see the following debug output:
The exception %s (0x [trythiswork]
Not very helpful, but it shows that logging itself works. This is followed up by something like
FailFast(1) tid(b230) 8007023E {Application Error}
causing the process to terminate. The WIL only recognizes exceptions of type std::exception, wil::ResultException, and Platform::Exception^. When it handles an unrecognized exception type it will terminate the process by default. This can be verified by commenting out the call to check_bool and instead throwing a standard exception (such as std::bad_alloc). This produces a program that will log exception details, but continue to execute.
The behavior can be customized by registering a callback for custom exception types, giving clients control over translating between custom exception types and HRESULT values. This is useful in cases where WIL needs to interoperate with external library code that uses its own exception types.
For C++/WinRT exception types (based on hresult_error) the WIL already provides error handling helpers that can be enabled (see Integrating with C++/WinRT). To opt into this all you need to do is to #include <wil/cppwinrt.h> before any C++/WinRT headers. When using precompiled headers that's where the #include directive should go.
With that change, the program now works as desired: It logs exception information for exceptions that originate from C++/WinRT, and continues to execute after the exception has been handled.

Why not every type are throw exceptions?

"Only the types that are inherited from the Throwable class can be thrown".
Could anybody explain me. Why not every type are throwable? If in doc there no mention about function can throw exception, it's mean that it do not have exception?
For example I thought that next try-catch block would work. But it is not.
try
{
writeln("(((((((((");
latestdtonpage = dts.sort!((a,b) => a>b).front; //latest date-time. from page.
}
catch(Exception e)
{
writeln("Can't select the latest Date from parsed date");
writeln(e);
}
But output in case of exception is next (no exception text):
(((((((((
core.exception.AssertError#C:\D\dmd2\windows\bin\..\..\src\phobos\std\array.d(73
9): Attempting to fetch the front of an empty array of DateTime
----------------
0x0051C4C9 in _d_assert_msg
0x00468E78 in pure nothrow ref #property #nogc #safe std.datetime.DateTime std.r
ange.__T11SortedRangeTAS3std8datetime8DateTimeS473app19StackOverflowParser5parse
MFAyaZ9__lambda2Z.SortedRange.front() at C:\D\dmd2\windows\bin\..\..\src\phobos\
std\range.d(8418)
0x0044F908 in void app.StackOverflowParser.parse(immutable(char)[]) at D:\code\T
rendoMetr\source\app.d(173)
0x0044F700 in app.StackOverflowParser app.StackOverflowParser.__ctor(app.DBConne
ct) at D:\code\TrendoMetr\source\app.d(150)
0x0044F199 in _Dmain at D:\code\TrendoMetr\source\app.d(33)
0x0052EDCA in D2rt6dmain211_d_run_mainUiPPaPUAAaZiZ6runAllMFZ9__lambda1MFZv
0x0052ED9F in void rt.dmain2._d_run_main(int, char**, extern (C) int function(ch
ar[][])*).runAll()
0x0052ECB5 in _d_run_main
0x00470198 in main
0x005667D1 in mainCRTStartup
0x76D1336A in BaseThreadInitThunk
0x772A9F72 in RtlInitializeExceptionChain
0x772A9F45 in RtlInitializeExceptionChain
Error executing command run: Program exited with code 1
How I can throw exception in this code?
Your code throws an AssertError, indicating that dts.sort!((a,b) => a>b) is empty, and you shouldn't call .front on it. Instead, query .empty first, and act accordingly when it's true.
AssertError inherits from Error which in turn inherits from Throwable but not from Exception. So catch(Exception e) doesn't catch it. And you should not catch Errors anyway, as they indicate that the program is in an unrecoverable error-state.
AssertError in particular signals a logic bug in your program. Here: calling .front on an empty range. Don't catch AssertError, but fix your code instead.

Also log every exception at error level

Using Groovy / Grails and log4j is there any way to ensure every exception thrown in the code is logged at error level.
Rather than having to find every catch block and explictly log it?
If not groovy / grails - a java suggestion will suffice.
Thanks
I don't believe there's any way to do this for handled exceptions, but you can do it for unhandled exceptions by adding the following to UrlMappings.groovy
"500"(controller: 'error')
Then create an ErrorController.groovy under grails-app/controllers
class ErrorController {
def index() {
Throwable exception = request?.exception?.cause
log.error 'something bad happened', exception
}
}

WinRt. UnhandledException handler. StackTrace is null

I have a project on WinForms with this code:
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
private void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{ }
The e.ExceptionObject contains full StackTrace.
In Win Store project:
this.UnhandledException += (s, e) =>{
{
MarkedUp.AnalyticClient.LogLastChanceException(e);
};
e.Exception.StackTrace is null.
Both exceptions were generated by this code:
int a=0;
....
try
{
int i = 1 / a;
}
catch (Exception exp)
{
throw;
}
Any Ideas?
The reference on MSDN suggests that this is a limitation: http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.application.unhandledexception
A notable limitation is that the UnhandledException event arguments don’t contain as much detail as the original exception as propagated from app code. Whenever possible, if the app requires specific processing of a certain exception, it’s always better to catch the exception as it propagates, because more detail will be available then. The UnhandledException event arguments expose an exception object through the Exception property. However, the type, message, and stack trace of this exception object are not guaranteed to match those of the original exception that was raised. The event arguments do expose a Message property. In most cases, this will contain the message of the originally raised exception.
Are you running the solution in Debug mode? There seems to be happening something in the App.g.i.cs file when you run the solution in Debug mode. When I run your sample in Release mode the stacktrace is available in the UnhandledException event.
In my test solution it breaks first here:
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
And after that one it goes to the UnhandledException handler that I have defined in the app.xaml.cs file. In Debug the stacktrace is gone, in Release mode the stacktrace and the exception details are there.

Groovy end exception different from exception thrown

I am running into an extremely strange behavior in Groovy. When I throw an exception from a closure in a Script, the end exception that was thrown was different.
Here are the code and the details:
public class TestDelegate {
def method(Closure closure) {
closure.setResolveStrategy(Closure.DELEGATE_FIRST);
closure.delegate = this;
closure.call();
}
public static void main(String[] args) {
// Make Script from File
File dslFile = new File("src/Script.dsl");
GroovyShell shell = new GroovyShell();
Script dslScript = shell.parse(dslFile);
TestDelegate myDelegate = new TestDelegate();
dslScript.metaClass.methodMissing = {
// will run method(closure)
String name, arguments ->
myDelegate.invokeMethod(name, arguments);
}
dslScript.metaClass.propertyMissing = {
String name ->
println "Will throw error now!"
throw new MyOwnException("errrrror");
}
dslScript.run();
}
}
class MyOwnException extends Exception {
public MyOwnException(String message) {
super(message);
}
}
Script.dsl:
method {
println a;
}
So the plan is that when I run the main() method in TestDelegate, it will run the DSL script, which calls for the method method(). Not finding it in the script, it will invoke methodMissing, which then invokes method() from myDelegate, which in turns invoke the closure, setting the delegate to the testDelegate. So far, so good. Then the closure is supposed to try printing out "a", which is not defined and will thus set off propertyMissing, which will will throw MyOwnException.
When I run the code, however, I get the following output:
Will throw error now!
Exception in thread "main" groovy.lang.MissingPropertyException: No such property: a for class: TestDelegate
Now, it must have reached that catch block, since it printed "Will throw error now!" It must have thrown MyOwnException too! But somewhere along the lines, MyOwnException was converted to MissingPropertyException, and I have no idea why. Does anyone have any idea?
P.S. if I remove closure.setResolveStrategy(Closure.DELEGATE_FIRST) from TestDelegate#method(), the code acts as expected and throws MyOwnException. But I really need the setResolveStrategy(Closure.DELEGATE_FIRST) for my DSL project. And I would prefer to know the root cause of this rather than just removing a line or two and see that it works without understanding why.
I think this is what essentially happens: With a delegate-first resolve strategy, the Groovy runtime first tries to access property a on myDelegate, which results in a MissingPropertyException because no such property exists. Then it tries propertyMissing, which causes a MyOwnException to be thrown. Eventually the runtime gives up and rethrows the first exception encountered (a design decision), which happens to be the MissingPropertyException.
With an owner-first resolve strategy, propertyMissing is consulted first, and hence MyOwnException is eventually rethrown.
Looking at the stack trace and source code underneath should provide more evidence.