SEH handler cause compiler warnings and errors - exception

I use a SEH handler in my code, like this:
__try
{
// code...
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
TRACE(_T("Exception"));
}
but get the following compiler errors:
e:\test.cpp(3310): warning C4509: nonstandard extension used: 'CMyClass::Test' uses SEH and 'iterator' has destructor
e:\test.cpp(3290): see declaration of 'iterator'
e:\test.cpp(3450): error C2712: Cannot use __try in functions that require object unwinding

It's just what the error message says: you can not use SEH in functions that require destructors to be called. You can always put that __try/__except block into a sub-function.
Edit: You can make that function static, but in my tests the compiler didn't inline it, not even with __forceinline.

Related

(Neko) "alc_cleanup: 1 device not closed" instead of error message

I'm making a game using Haxe and targeting neko. Any uncaught exception leads to alc_cleanup error.
The problem is, this error blocks the output of the exception details.
It's annoying because I use assertions so I can't find out which one threw an exception if one of the tests fail.
Any help here?
The alc_cleanup error simply happens because an OpenAl audio device in use (by your game or an underlying framework) hasn't been closed before terminating the program (due to the uncaught exception).
If you can, you might want to catch and log that exception yourself to prevent it from being corrupted by the alc_cleanup error:
static function main()
{
try {
// do stuff
} catch (e:Dynamic) {
trace('ERROR: $e');
trace(haxe.CallStack.toString(haxe.CallStack.exceptionStack()));
Sys.exit(1);
}
}
You could also:
try to find the proper API in the frameworks you use to destroy the OpenAl context
neko.Lib.rethrow the exception after doing the necessary cleanup yourself

Why isn't my exception being caught?

This is the stack trace I get:
[Fault] exception, information=Error: Directory id 3 already in use
at cantrips.assets.index::AssetIndex/dirIdChanged()[/home/luismasuelli/Proyectos/flash-assets-index-ritual/assets-index-loader/src/cantrips/assets/index/AssetIndex.as:72]
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at cantrips.assets.index::AssetDirectory/set id()[/home/luismasuelli/Proyectos/flash-assets-index-ritual/assets-index-loader/src/cantrips/assets/index/AssetDirectory.as:68]
at Main/updateSelectedDirectory()[/home/luismasuelli/Proyectos/flash-assets-index-ritual/assets-index-editor/src/Main.mxml:192]
at Main/__dirUpdateCurrent_click()[/home/luismasuelli/Proyectos/flash-assets-index-ritual/assets-index-editor/src/Main.mxml:401]
This is the implementation of Main/updateSelectedDirectory():
private function updateSelectedDirectory():void {
try {
var newId:uint = uint(dirId.text);
var newName:String = StringUtil.trim(dirName.text);
var selectedDirectory:AssetDirectory = assetBrowserTree.selectedItem as AssetDirectory;
if (selectedDirectory) {
selectedDirectory.id = newId;
selectedDirectory.name = newName;
assetBrowserTree.expandItem(selectedDirectory.parent, false);
assetBrowserTree.expandItem(selectedDirectory.parent, true);
}
} catch (error:Error) {
Alert.show(error.message, "Cannot update");
}
}
Why is not the exception being caught by try {} catch(error:Error) {}?.
The exception is an exception created by me, with a well-understood scenario where it is triggered (I created the exception and designed those scenarios and I am testing them; exception is triggered as I expect). I also tried using the exact name of the exception (AssetIndexError) in the catch block, and no confusion or ambiguous name exists (this means: there's no another AssetIndexError class declared elsewhere I could be importing instead of this).
Explanation:
cantrips.assets.index is code I have control over.
Main/* is the main window. I also have control over that code.
Screenshot:
If you look at your stack, you'll see the error is not being thrown in the code shown (which is near the bottom of the stack), but here:
dirIdChanged at AssetIndex.as:72
Further down in the stack you'll see the following:
at flash.events::EventDispatcher/dispatchEvent()
This means that stack was asynchronous in between AssetDirectory.set id() and
AssetIndex.dirIdChanged()
When you add an event handler, all code in the current block will usually run prior to the event handler code (as they are not in the same thread).
So in this case, all your code in the try/catch will have run before the event handler's code - which is why the error is not being caught.
Any time you are handling an event, you will need to have another try/catch, or use an asynchronous error handling technique.
This is a complement the OP made to the accepted answer.
The main reason of this trouble is that I did not understand how the event flow is done.
The event flow is asynchronous, and I thought as it being synchronous. If the event flow was synchronous, it is not hard to think that what I intended was right: The exception could be thrown in the same execution stack and everything would be fine (i.e. a method calls another method, such method calls a third method, blah blah blah exception and explosion).
When the event flow is asynchronous as ActionScript flow is, the exception will be triggered in another execution stack, but somehow the information provided is misleading as it should as if the execution stack was the same.
The solution I implemented: A dumb object (i.e. a dumb new class) which acted like EventDispatcher but being synchronous: .dispatch() would not post an event execution to the event flow, but instead execute by itself the registered event handlers, as a loop over the handlers, and calling each handler by hand, without the possibility of having stuff like event.target populated in the handlers.
Althought this design could be seen as bad from many points of view I would agree with, in this case it fit my needs of handlers throwing exceptions and code executed synchronously.

Exceptions in Lablgtk callbacks

In Lablgtk, whenever there is an exception in a callback, the exception is automatically caught and an error message is printed in the console, such as:
(prog:12345) LablGTK-CRITICAL **: gtk_tree_model_foreach_func:
callback raised an exception
This gives no stack trace and no details about the exception, and because it is caught I cannot retrieve this information myself.
Can I enable more detailed logging information for this case? Or prevent the exception from being caught automatically?
I guess the best way to do so is to catch your exception manually and handle it yourself.
let callback_print_exn f () =
try f () with
e -> my_exn_printer e
Assuming val my_exn_printer : exn -> unit is your custom exception printer, you can simply print your callbacks exceptions by replacing ~callback:f by ~callback:(callback_print_exn f) in your code.
Of course, you can also with that method send that exception to another
thread, register a "callback id" that would be passed along with your exception...
About the stack trace, I'm not sure you can retrieve it easily. As it's launched as a callback, you probably want to know the signal used and that can be stored in your callback handler.
I had another similar issue, but this time it was harder to find where to put the calls to intercept the exception.
Fortunately, this time there was a very specific error message coming from the Glib C code:
GLib-CRITICAL **: Source ID ... was not found when attempting to remove it`
Stack Overflow + grep led me to the actual C function, but I could not find which of the several Lablgtk functions bound to this code was the culprit.
So I downloaded the Glib source, added an explicit segmentation fault to the code, compiled it and used LD_LIBRARY_PATH to force my modified Glib version to be loaded.
Then I ran the OCaml binary with gdb, and I got my stack trace, with the precise line number where the Lablgtk function was being called. And from there it was a quick 3-line patch.
Hacks like this one (which was still faster than trying to find where to intercept the call) could be avoided by having a "strict mode" preventing exceptions from being automatically caught. I still believe such a switch should be available for Lablgtk users, and hope it will eventually be available.

How error handling is done in Jcuda?

In CUDA we can get to know about errors simply by checking return type of functions such as cudaMemcpy(), cudaMalloc() etc. which is cudaError_t with cudaSuccess. Is there any method available in JCuda to check error for functions such as cuMemcpyHtoD(), cuMemAlloc(), cuLaunchKernel() etc.
First of all, the methods of JCuda (should) behave exactly like the corresponding CUDA functions: They return an error code in form of an int. These error codes are also defined in...
the cudaError class for the Runtime API
the CUresult class for the Driver API
the cublasStatus class for JCublas
the cufftResult class for JCufft
the curandStatus class for JCurand
the cusparseStatus class for JCusparse
and are the same error codes as in the respective CUDA library.
All these classes additionally have a static method called stringFor(int) - for example, cudaError#stringFor(int) and CUresult#stringFor(int). These methods return a human-readable String representation of the error code.
So you could do manual error checks, for example, like this:
int error = someCudaFunction();
if (error != 0= {
System.out.println("Error code "+error+": "+cudaError.stringFor(error));
}
which might print something like
Error code 10: cudaErrorInvalidDevice
But...
...the error checks may be a hassle. You might have noticed in the CUDA samples that NVIDIA introduced some macros that simplify the error checks. And similarly, I added optional exception checks for JCuda: All the libraries offer a static method called setExceptionsEnabled(boolean). When calling
JCudaDriver.setExceptionsEnabled(true);
then all subsequent method calls for the Driver API will automatically check the method return values, and throw a CudaException when there was any error.
(Note that this method exists separately for all libraries. E.g. the call would be JCublas.setExceptionsEnabled(true) when using JCublas)
The samples usually enable exception checks right at the beginning of the main method. And I'd recommend to also do this, at least during the development phase. As soon as it is clear that the program does not contain any errors, one could disable the exceptions, but there's hardly a reason to do so: They conveniently offer clear information about which error occurred, whereas otherwise, the calls may fail silently.

Problem with FlexUnit4

I"m a bit confused because FlexUnith 4's behavior. When I use fail() in try-catch body fail method is just ignored.
[Test]
public function extend():void
{
try {
fail("This should fail");
} catch(er:Error) {}
}
I suppose this one should fail as there is no way around it, but it succeeds and turns green. Whatam I doing wrong? When i put fail() before try-catch block it fails as it is suposed to. BTW using Flash builder 4.
The way assertions are signaled to the framework is through exceptions. fail sends the failure signal using an exception too. That, and the fact that Error is the base class for all exceptions means that no exception will ever reach the framework (your try/catch block catches all excpetions), which means that the test didn't fail.