Why do I get CA1806 when I catch exception in C++/CLI? - visual-studio-2010

I've recently upgraded my project from Visual Studio 2008 to Visual Studio 2010.
By enabling Code Analysis and compiling in Release, I'm getting warning CA1806: Do not ignore method results.
I've managed to reduce the code that produces the warning to this code:
.h file:
public ref class Foo
{
public:
void Bar();
};
.cpp file:
void Foo::Bar()
{
try
{
}
catch (const std::exception&) // here I get the warning
{
}
}
the warning:
CA1806 : Microsoft.Usage :
'Foo::Bar(void)' calls
'Global::__CxxRegisterExceptionObject(void*,
void*)' but does not use the HRESULT
or error code that the method returns.
This could lead to unexpected behavior
in error conditions or low-resource
situations. Use the result in a
conditional statement, assign the
result to a variable, or pass it as an
argument to another method.
If I try to use the exception value or do catch(...) the warning still appears. If I catch managed exceptions instead or compile in Debug I don't get the warning.
Why do I get this warning?
UPDATE
I've decided to open a bug report on Microsoft Connect.

This is a Visual Studio 2010 bug.
As you can see in the bug report, Microsoft reproduced the bug and has decided to postpone the resolution with no workaround.
You are welcome to vote for the bug so maybe Microsoft will decide to resolve it sooner.

Could be because you didn't call any code that could throw.

Related

Visual Studio exits on assertion failure with no error message

I have a very similar problem to this post, but with a single-threaded C++ program: when an assertion fails during debugging in Visual Studio 2013, the debugger exits immediately without showing the assertion failure message box, which is supposed to look something like this:
(This picture is not from my own code.)
The only error message is:
The program '[5156] myprogram.exe' has exited with code 3 (0x3).
which makes it nearly impossible to figure out where the assertion failure occurred since the code base is very large.
The response to the linked question suggested adding a call to:
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
at the beginning of the program, so that the assertion error is at least printed to the output window. However, this is not only hacky, but also not necessary for any other program I have debugged in Visual Studio.
This is not my own Visual Studio project, and I'm wondering if there is a rogue setting somewhere. I have enabled "Break when an exception is thrown" for assertion errors in Debug -> Exceptions, so that is not the issue.
How can I force the "Debug Assertion Failed!" message box to appear when an assertion fails?
In my case, the problem was that Configuration Properties -> C/C++ -> Code Generation -> Runtime Library was set to "Multi-threaded" for both the Debug and Release builds. The correct setting is "Multi-threaded Debug" for the Debug build and "Multi-threaded" for the Release Build.
You can try set a custom invalid_parameter_handler.
I encounter a similar problem when using vs2017.
the following code will not trigger debug assertion fail notice when i use my vs2017 to debug.
char dst[128] = { 0 };
char src[256] = { 0 };
memcpy_s(dst, sizeof(dst), src, sizeof(src));
but when i set a custom handler. it works. Checkout this link

Why can't I use STAThread attribute in C++/CLI?

I wan to use the STAThread attribute on my the main thread of my program. However, Visual Studio says it cannot find it. I have tried references necessary assemblies and using proper namespace, but it just can't find it.
Edit:
I have been able to get to work successfully after manually creating a thread with the
ApartmentState to STA. I think this is the equivalent to setting the thread, be it the main thread, but not exactly because i'm creating another thread. Anyone have another way to do this.
Here is the code:
void threadStart ()
{
Application::Run (gcnew GraphicsForm());
}
[System::STAThread] // This will not work!
int main(array<System::String ^> ^args)
{
Thread ^t = gcnew Thread(gcnew ThreadStart (threadStart));
t->ApartmentState = ApartmentState::STA;
t->Start();
return 0;
}
When I create a new C++/CLI project in Visual Studio 2012 with only a single main() function and then add [System::STAThread] in front of main(), it compiles and runs without a problem. To me, this means that it is most likely a settings difference between projects.
My recommendation is to do the same thing. Create a new C++/CLI project, add [System::STAThread] and see if it has any issues. If not, then you're at the point of checking the differences between the two projects to determine why one works properly and the other is giving you an error.

JIT Debugging hiding bug in C# app

I have an application that works fine under visual studio.
However, when I run it stand-alone, a certain operation which throws an exception isn't handled. (The exception is expected, but it's correctly handled under VS.)
I added a line to my machine.config to enable JIT debugging, to try and locate the problem, but I then could not recreate the bug (the exception was handled correctly). Deleting the line causes the bug to come back.
How should I start looking for the cause?
The relevant parts (I believe) of my code (edited to remove extraneous detail) are at http://pastebin.com/i2zLCTn5.
Some suggestions that may affect how your code is behaving in the different environment of Visual Studio:
Stop Visual Studio turning off the JIT Optimizer when you run your program under Visual Studio.There's an option called "Suppress JIT optimization on module load"...you want to try changing that to be NOT ticked.
For more details on what the option does see here:
http://msdn.microsoft.com/en-us/library/ms241594.aspx
Turn off the "hosting process" ...http://msdn.microsoft.com/en-us/library/ms185330(v=vs.80).aspx
Run the Program, then "Attach to Process" (it then won't be in a hosting process, and the modules will have been loaded and JIT optimized).
In the Exceptions dialog tick the "Thrown" check box of the Exception that is being eated/handled....so that you can track down who is handling it and why. You will need to install the NET Framework Sourcecode if the Exception is being handled there so that you can see the details.
You could have a try at running it under WinDBG instead (it may behave differently as you then won't be running under a hosting process i.e. .vshost)....make sure you have the extension DLL PSSCOR4 (if using .NET 4) so that you can make sense of things.
So, I discovered - or rather, a friend explained - the cause of this problem:
You cannot catch exceptions across threads when JIT debugging is disabled, even if execution appears to flow correctly.
The exception was being thrown in a Form.Closing event handler:
form.Closing += new delegate
{
switch(form.DialogResult)
{
case DialogResult.OK:
// do stuff;
break;
case DialogResult.Cancel:
throw new AbortOperationException();
}
}
// ...
try
{
mainForm.Invoke(new Function<Form, DialogResult>(form.ShowDialog), mainWindow);
}
catch (AbortOperationException)
{
// handle abort
}
The solution was to refactor slightly to eliminate the throw:
form.Closing += new delegate
{
if (form.DialogResult == DialogResult.OK)
{
// do stuff
}
}
// ...
var result = (DialogResult)mainForm.Invoke(new Function<Form, DialogResult>
if (result == DialogResult.Cancel)
{
// handle abort
}

Visual Studio 2010 UnhandledException, ThreadException error handling?

In my code I had an error that was catched by following exceptions while program was running. However when I was running program in Visual Studio when the error was happening application was simply exiting without any error (other errors usually bring me to the problematic line).
if (ApplicationDeployment.IsNetworkDeployed) {
AppDomain.CurrentDomain.UnhandledException += currentDomainUnhandledException;
Application.ThreadException += applicationThreadException;
}
Of course if i remove the if i get this exception handling done by my methods which simply uses MessageBox to show the error. Is there a way to force Visual Studio to catch this error like it catches other types of errors?
Only by using Debug + Exceptions, Thrown checkbox. That makes the debugger stop on the "first chance". At the point the exception is thrown. You typically want to do this:
if (!System.Diagnostics.Debugger.IsAttached) {
// Subscribe the events
//...
}
Note that this already works that way for Application.ThreadException, Winforms already avoids catching exceptions if it sees a debugger. For the exact same reason.

How to temporarily deactivate all try / catch blocks?

Is there a possibility to deactivate / activate all try catch blocks in the whole project as easy as clicking a button?
I need this for debugging when I don't want the catch block to handle the exception, but instead prefer that VS breaks into the code as if the try catch block was not there.
At the moment I am commenting out the try/catch blocks but this is inefficient.
Environment: VS 2008 with C# as language.
To catch exceptions the moment they're thrown ("first-chance exceptions" in Win32 parlance):
in VS2008: go to Debug, Exceptions...
by VS2015: this has been moved to Debug > Windows > Exception Settings
Then check the box Thrown for Common Language Runtime Exceptions.
There is no way to deactivate try/catch blocks.
However, for debug purposes, if you want to break as soon as a particular type of exception is thrown, you can get Visual Studio to do that (Debug -> Exceptions; select the exception type you're interested in and check the "Thrown" box).
Thought about this today and found an other solution. The advantage of this is that the IDE will stop at the exact point of the occuring exception.
Somewhere globaly defined:
Namespace Global.System
Public Class NeverOccurException
Inherits Exception
End Class
End Namespace
At the beginning of each source code file:
#If DEBUG
Imports CatchAtReleaseException = System.NeverOccurException
#Else
Imports CatchAtReleaseException = System.Exception
#End If
Usage:
'Compiled in DEBUG-Mode the TryCatch is "disabled", because the
'the ALIAS CatchAtReleaseException is set to "NeverOccurException"
'Compiled as RELEASE the TryCatch is "enabled", because the ALIAS
'is set to the regular "System.Exception"
Public Sub SampleSub()
Try
'...
Catch ex As CatchAtReleaseException
End Try
End Sub
Have fun with it,
Greetings,
Ted
If you want to do in the IDE, Debug -> Exceptions is the dialog where you can ask the IDE to break when a specific/category/all exceptions are thrown.
You can change the way Visual Studio breaks when an exception occurs. By default, it breaks on unhandled exceptions. If you go to menu Debug > Exceptions, you can uncheck Common Language Runtime Exceptions and make other changes in the IDE's behavior when exceptions occur. For example, you can have it break on only one kind of exception; there's a long list there.
I have done this on rare occasions when trying to debug.

Resources