Why I get First-chance exception if no one calls the function? - c++

Suddenly my code started to throws an exception First-chance exception at 0x7731c41f in VideoPlayer.exe: Microsoft C++ exception: GenICam::RuntimeException at memory location 0x0018f5dc.. I could not find where exactly it throws from, so I commented all in main function and everything outside the main. I started to uncomment blocks of code one by one whilst the code in main remains commented. While doing it I noticed that there is function A that when it is commented there is no exception, but when it's uncommented it throws the exception above.
I don't understand how it can cause exeception if it's not called ( I placed breakpoint in it and code in main is commented)?

You function will be used during the static initialization.
Take the following example:
#include <iostream>
bool static_func()
{
std::cout << "Before main" << std::endl;
return true;
}
static const bool b = static_func();
int main()
{
std::cout << "We are main" << std::endl;
return 0;
}
Since you only see a first chance exception it will be caught and handled. I have seen such constructs in abstract factories for example, where the factory configures itself.
The reason why your breakpoint is not hit must be something else.

In VS, Debug menu, Exceptions... check the throw column for the matching type. Then start debugging and it will stop exactly where throw happens. And you can look around why.

Related

Catching/Handling exceptions thrown in AngelScript functions

I'm playing around with AngelScript, and one thing I can't seem to wrap my head around is how to catch exceptions thrown from C++ but called from AngelScript. Here's what I've got so far:
// test.as
void main()
{
print("Calling throwSomething...");
throwSomething();
print("Call finished");
}
void print(string) and void throwSomething() are two functions registered to the engine, source below. As per the AngelScript docs:
Application functions and class methods registered with the script engine are allowed to throw C++ exceptions. The virtual machine will automatically catch any C++ exception, abort the script execution, and return control to the application.
Here's the example code provided for handling exceptions:
asIScriptContext *ctx = engine->CreateContext();
ctx->Prepare(engine->GetModule("test")->GetFunctionByName("func"));
int r = ctx->Execute();
if( r == asEXECUTION_EXCEPTION )
{
string err = ctx->GetExceptionString();
if( err == "Caught an exception from the application" )
{
// An application function threw an exception while being invoked from the script
...
}
}
I pretty much verbatim copied this code into my editor and tried to run it. Unfortunately, even though I wrapped the call to Execute in a try-catch block, I still get this output:
(AngelScript) Calling throwSomething...
(C++) throwSomething Entered...
libc++abi.dylib: terminating with uncaught exception of type std::runtime_error: Assert(1 == 0) failed, line 68
Abort trap: 6
For completeness' sake, here's the code for throwSomething and print:
void throwSomething()
{
cout << "(C++) throwSomething Entered...\n";
Assert(1 == 0); // will throw an exception
cout << "(C++) throwSomething Exiting...\n";
}
void print(string s)
{
cout << "(AngelScript) " << s << "\n";
}
So, I'm feeling a little stuck. I tried registering an exception translation function (see linked doc) in hopes that would help, but I still got the same results. From looking at Xcode's debugger, the exception appears to happen in the main thread-- so I'm unsure why neither my code or the code in the AngelScript library itself catches the exception.
So, I guess my question is: 1) how can I either catch the exception within my program, or 2) If I can't catch it from within the program, how can I otherwise handle it without the program crashing?
I'm running this on a ~2015 MacBook Pro running MacOS 10.14.6 and AngelScript version 2.33.0, if that's relevant.

How to catch exception without throw

There is a CRASH in Function() due to some exceptions so, throw X would not be called. In this case how to call catch block to handle exceptions?
NOTE: we can't modify the code in Function() definition
Sample code:
cout << "Before try \n";
try {
abc->Function(); //Here is CRASH
throw x;
cout << "After throw (Never executed) \n";
}
catch (...) {
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
So can anyone help me out for this?
A "CRASH" is not an exception. It is Undefined Behaviour. Absolutely anything could have happened. You are lucky that the system detected it. It could have formatted your disk or summoned daemons out of your nose. Instead the system is only shutting down the process to prevent further damage.
The system might even be so kind as to let you define what to do instead of shutting down the process. The way to define it is system specific. In Unix, you need to install signal handler (the advanced way), in Windows you use structural exceptions.
But the problem is that if the function crashed, there is no way to tell how big mess it left the memory of the process in. You really have to fix the crash. A crash is always a bug.
The fact that a crash is inside that function does not automatically mean the bug is in that function. Most crashes I've seen happened in standard library functions, but they were not bugs in standard library. They were caused by incorrect use of those functions, or sometimes incorrect use of something different much earlier in the program. Because when you invoke Undefined Behaviour, there's no telling when it will cause a crash. Especially buffer overruns and writes to uninitialized pointers tend to cause crashes eventually when some unrelated code wants to use the variable that was overwritten.
That said if the bug is indeed in that function and you can't modify it, you will have to get somebody who can or find an alternative that works better. Because there's no way the program is going to work correctly otherwise.
There's an aditional '}' in the try block in your code. Not sure whether that was an error in typing the code or from another higher level block.
The catch(...){} block will be executed when any unhandled exception is thrown inside the try {} block. It doesn't matter whether the exceptions are thrown directly under the block or somewhere deep down in other function calls in the block.
cout << "Before try \n";
try
{
abc->Function1(); //A potential for crash
abc->Function2(); //Another potential for crash
abc->Function3(); //Another potential for crash
// Do some checks and throw an exception.
throw x;
cout << "After throw (Never executed) \n";
}
catch (...)
{
// This will catch all unhandled exceptions
// within the try{} block. Those can be from
// abc->Function1(), abc->Function2(), abc->Function3(),
// or the throw x within the block itself.
cout << "Exception Caught \n";
}
cout << "After catch (Will be executed) \n";
Hope that is helpful.
Here us the meaning of try and catch
try {
//[if some ABC type exception occur inside this block,]
}catch (ABC) {
//[Then, Do the things inside this block.]
}
So
after the exception occur in your abc->Function(); flow will directly jump in to catch block so write there what you need to do. as example.
try {
abc->Function(); //Here is CRASH
throw x;
cout << "After throw (Never executed) \n";
}catch (Exception ex) {
cout << "Exception Caught \n";
throw ex;
}
actually throw x; doesn't have any use here. because if your abc->Function(); worked fine, then it will throw an exception. so just remove that line.
the code you have written works exactly true . the compiler when see the throw command every where in the try{} it will go to the catch(){} so the cout << "After throw (Never executed) \n"; won't execute and then the code after the catch(){} will execute
for reading more about this case here is the link trycatch
If you got exception ,
abc->Function(); //Here is CRASH
You will enter in catch(...) block.
If you are using Windows OS, for OS generated exceptions you also need to use __try/__catch

What does throw do when not in used with try and catch?

What does throw do when not used with try and catch? Like:
if (IsEmpty()) throw "Stack is empty, Cannot delete";
Does it get printed in console?
But when throw contains some int or char as its arguments, it is thrown to catch; what happens in this case?
The C++ runtime will have something along the lines of (this is NOT exactly how it looks, but you can think of it as working this way, unless you are working on something very special):
void BeforeMain()
{
try
{
int res = main();
exit(res);
}
catch(...)
{
cout << "Unhandled exception. Terminating..." << endl;
terminate();
}
}
You are allowed to do that, and it will not be caught anywhere within your code if you have not put an explicit try catch block.
Windows uses a SEH mechanism to handle , where you could have an uncaught exception filter to figure out about the same
See this post for more details
Catching exceptions thrown without try/catch

How to cause C++ throw to dump core if the exception would be handled by a particular catch block

Is there a way to cause a throw in C++ to dump core at the throw site if the thrown exception would be handled by a certain catch block? I would like something similar to what happens with g++ when an exception reaches the top level.
For example, I would like something like this:
try {
bar();
try {
foo();
} catch(...) {
# pragma dump_at_throw_site
}
} catch(...) {
std::cerr << "There was a problem" << std::endl;
}
This way, if any exception thrown from foo() or its callee's that reaches the call-site of foo() would cause a core dump at the throw site so one can see who threw the exception that made it to the to this level.
On the other hand, exceptions thrown by bar() would be handled normally.
Yes,it can in Windows. I don't know Linux, suppose it can also.
We can register a Exception Handler function to response the throw before the catch
Here is the code example:
#include <iostream>
#include "windows.h"
#define CALL_FIRST 1
LONG WINAPI
VectoredHandler(
struct _EXCEPTION_POINTERS *ExceptionInfo
)
{
UNREFERENCED_PARAMETER(ExceptionInfo);
std::cout <<"VectoredHandler"<<std::endl;
return EXCEPTION_CONTINUE_SEARCH;
}
int main()
{
PVOID handler;
handler = AddVectoredExceptionHandler(CALL_FIRST,VectoredHandler);
try {
throw 1;
}catch(...)
{
std::cout <<"catch (...)"<< std::endl;
}
RemoveVectoredExceptionHandler(handler);
std::cout << "end of main"<<std::endl;
return 0;
}
The outputs of code are:
VectoredHandler
catch (...)
end of main
So,you can dump core int the function VectoredHandler.
The VectoredHandler is called after the debugger gets a first chance notification, but before the system begins unwinding the stack.
And if your purpose is just to debug the problem issue, then you can rely on the debugger feature to handle the first chance exception, don't need dump the application.
For your information, you may need know What is a First Chance Exception? in windows to understand how windows dispatch the exception.

What could be overriding the return code from main()?

I have a rather odd occurrence happening that I haven't been able to nut out yet.
I have test case that is supposed to catch errors and return the appropriate error code from main, but /sometimes/ on test runs the program returns 0 even when the error code is non zero.
The exception class thrown is:
class exit_request {
public:
explicit exit_request(int code = 0) : m_code(code) {}
int code() const { return m_code; }
private:
int m_code;
};
The test case code is:
int main(int argc, char* argv[])
{
try {
// Do some test case stuff
// Eventually, due to the supplied command line arguments,
// we expect an exit_request() to be thrown from within
// library code.
}
catch (exit_request& exp) {
std::cout << "Exit Request:" << exp.code() << std::endl;
return exp.code();
}
catch (std::exception& err) {
std::cout << "Error: " << err.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
In many runs of this test case, everything works as expected: The exit_request() exception is thrown, caught, exp.code() is printed (its value is 2), and the return code from the process is 2.
However, very occasionally, the return code from the process is 0 (i.e. no failure), even though exp.code() is printed as 2.
Can anyone help explain a situation in which this can occur? i.e. the return value from main is changed from non-zero to zero before the process exits?
This is occurring on Windows 7 (x64), with MSVC++ 2010 Express, building a x86 (32-bit) application. I have not seen this odd failure on any of our other Windows or Linux platforms, or compilers, but that doesn't necessarily mean it couldn't happen in those environments.
If you have any atexit handlers that call exit(0), or any static-storage-duration objects whose destructors do that, it might explain what you're seeing. They get executed after your return statement. It's undefined behavior, which could explain why you only see it happen sometimes.
Maybe you are not throwing the exception correctly...
I mean that from the function called or processing done in try block, you are throwing exception of some other type.
Try to write a default catch block for that.