I am in a situation where I'm using memmove_s() to copy a buffer in a safer way.
So, at first, I just used the memmove_s() and I tested when destination size is greater than the source size and thrown an exception. Then, I put it inside a try/catch and it didn't catch the exception. The reason is that I am using a C code inside a C++ code. So, I found a Microsoft solution using __try/__except block. However, I got the error Cannot use __try in functions that require object unwinding.
That's a part of my code:
int filter(unsigned int code, struct _EXCEPTION_POINTERS* ep)
{
puts("in filter.");
if (code == ERANGE)
{
cout << "_DestinationSize >= _SourceSize" << endl;
return EXCEPTION_EXECUTE_HANDLER;
}
else
{
cout << "didn't catch the exception, unexpected." << endl;
return EXCEPTION_CONTINUE_SEARCH;
};
}
string GetValue()
{
return string("Value");
}
extern "C" void get_str_value(string src, char* dest, unsigned int destSize)
{
__try
{
auto r = memmove_s((void*)dest, destSize + 1, src.c_str(), src.size() + 1);
cout << "r=" << r << endl;
}
__except (filter(GetExceptionCode(), GetExceptionInformation()))
{
std::cout << "Exception" << std::endl;
}
}
So, is there any way to solve that problem?
Related
The following code will print 0 and ends:
// version 1
#include<future>
#include<iostream>
using namespace std;
int main(){
promise<int> p;
auto f = p.get_future();
p.set_exception(current_exception());
try {
cout << f.get() << endl;
} catch (const exception& e) {
cout << "caught future set exception\n";
}
return 0;
}
Well, seems p.set_exception(current_exception()); didn't cause any issue. But when I change it to be:
// version 2
#include<cassert>
#include<future>
#include<iostream>
using namespace std;
int main(){
promise<int> p;
auto f = p.get_future();
string msg = "test promise";
async([&] { // new code which version 1 didn't have
try {
throw runtime_error(msg);
} catch (...) {
cout << "caught exception 1\n";
try {
p.set_exception(current_exception());
} catch (...) {
cout << "caught exception 2\n";
}
}
}).wait(); // end new code
try {
cout << f.get() << endl;
} catch (const exception& e) {
cout << "caught future set exception\n";
assert(e.what() == msg);
}
return 0;
}
It will run and print:
caught exception 1
caught future set exception
Just wonder how/when does a std::promise fall into error/exception state so that its get_future().get() will throw exception?
What's the main reason of my version 2 code that p.set_exception() causes f.get() issue, while version 1 code has no problem?
Thanks.
I am Implementing some program error exception catching and it's not getting to work properly thus I have seen any error in my code and compiler is also not showing any warnings and error.
The programs build successfully but ignored the exceptions.
#include <iostream>
#include <string>
using namespace std;
void wrongUsage()
{
bool erroCode = true;
bool errorMessge = true;
bool stringError = true;
if(erroCode)
{
throw 7;
}else if (errorMessge)
{
throw "Something went wrong in Character message";
}else if(stringError)
{
throw string ("Something else wrong happened in the string area");
}
}
void programErrorExceptions()
{
void wrongUsage();
}
int main()
{
try {
programErrorExceptions();
}
catch (int err)
{
cout << "Code Exception occurred: " << err << '\n';
}
catch (char const *err)
{
cout << "Msg Exception occurred: " << err << '\n';
}
catch (string &err)
{
cout << "Strmsg Exception occurred: " << err << '\n';
}
return 0;
}
correct the following
void programErrorExceptions()
{
void wrongUsage();
}
to
void programErrorExceptions()
{
wrongUsage();
}
I've searched extensively but there seems not to be a satisfying answer to this question online. So I'm posting again this problem in case someone has found a solution.
I have written a C++ code that is supposed to call some Matlab code. I have compiled all my Matlab files using the following command:
mcc -N -W cpplib:libRTR2 -T link:lib RTR.m -v
I have included the header, DLL and LIB files created by above command in the 'Header Files'for my Visual Studio project. I have also includde mclmcrrt.lib, mclmcrrt.h and mclcppclass.h in the same.
Here is my C++ code:
#define BZZ_COMPILER 3
#include <stdint.h>
#include "./hpp/BzzMath.hpp"
#include "libRTR2.h"
#include <iostream>
#include "mclmcrrt.h"
#include "mclcppclass.h"
double RTRtest(BzzVector &x)
{
x(1);
mwArray out(1,1);
try {
// create input
double a[] = { x[1] };
mwArray in1(1, 1, mxDOUBLE_CLASS, mxREAL);
in1.SetData(a, 1);
// call function
RTR(1, out, in1);
// show result
std::cout << "objFun" << std::endl;
std::cout << out << std::endl;
double F[1];
out.GetData(F, 1);
for (int i = 0; i<1; i++) {
std::cout << F[i] << " " << std::endl;
}
}
catch (const mwException& e) {
std::cerr << e.what() << std::endl;
return -2;
}
catch (...) {
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
// cleanup
return out;
}
int optim()
{
if (!mclInitializeApplication(NULL, 0)) {
std::cerr << "could not initialize the application" << std::endl;
mclGetLastErrorMessage();
return -1;
}
if (!libRTR2Initialize()) {
std::cerr << "Could not initialize the library" << std::endl;
return -1;
}
bzzFilePrint("BzzRobustMinimization.txt");
BzzVector Xmin(1, 2000.);
BzzVector Xmax(1, 5000.);
BzzVector X0(1, 2000.);
double F0 = RTRtest(X0);
BzzMinimizationRobust m(X0, F0, RTRtest, Xmin, Xmax);
m();
m.BzzPrint("Results");
libRTR2Terminate();
mclTerminateApplication();
}
int main()
{
mclmcrInitialize();
return mclRunMain((mclMainFcnType)optim, 0, NULL);
}
And when I try to debug it I obtain this error:
Access Violation Error
I know it is related probably to trying to pass a null pointer to one of my functions, but being no expert in C++ I'm struggling to find where the error lies. Any help is greatly appreciated!
I had this funny idea last night, to trap hardware exceptions and throw a C++ exception instead. Thought that might be useful for things like FPU exceptions, which normally either crash, or silently return NaN and then cause unexpected behaviour. A C++ exception would be far more desirable here.
So I've been hacking all morning and finally got it to work. Well, almost. The compiler still doesn't realize that arithmetic operations can now throw C++ exceptions, and will silently discard the try/catch block around it. It does work when the exception occurs in a function.
void throw_exception()
{
throw std::runtime_error("Division by zero!");
}
__attribute__((noinline))
void try_div0()
{
cout << 1 / 0 << endl;
}
int main()
{
// this class traps a hardware exception (division by zero, in this case) and calls the supplied lambda function.
// uh, no, you probably don't want to see the assembly code behind this...
exception_wrapper div0_exc { 0, [] (exception_frame* frame, bool)
{
if (frame->address.segment != get_cs()) return false; // only handle exceptions that occured in our own code
frame->stack.offset -= 4; // sub <fault esp>, 4;
auto* stack = reinterpret_cast<std::uintptr_t *>(frame->stack.offset); // get <fault esp>
*stack = frame->address.offset; // mov [<fault esp>], <fault address>;
frame->address.offset = reinterpret_cast<std::uintptr_t>(throw_exception); // set return address to throw_exception()
return true; // exception handled!
} };
try
{
// cout << 1 / 0 << endl; // this throws, as expected, but calls std::terminate().
try_div0(); // this exception is caught.
}
catch (std::exception& e)
{
cout << "oops: " << e.what() << endl;
}
}
I realize this is an unusual question... but is there any way I could make this work? Some way to tell gcc that exceptions can occur anywhere?
I'm compiling with djgpp which (I believe) uses DWARF exception handling.
edit: I just found gcc flags -fnon-call-exceptions and -fasynchronous-unwind-tables, which appear to be what I'm looking for. But it still doesn't work...
edit: Now using the previously mentioned gcc flags, it does catch when the exception occurs in between two function calls:
inline void nop() { asm(""); }
// or { cout << flush; } or something. empty function does not work.
int main()
{
/* ... */
try
{
nop();
cout << 1 / 0 << endl;
nop();
}
/* ... */
}
edit: Nested try/catch blocks have the same effect, no exception is caught unless the trapped instruction is preceded by a function call.
inline void nop() { asm(""); }
void try_div(int i)
{
try
{
// this works, catches exception in try_div(0).
nop();
cout << 1 / i << endl;
try_div(i - 1);
// without the first nop(), calls std::terminate()
//cout << 1 / i << endl;
//try_div(i - 1);
// reverse order, also terminates.
//if (i != 0) try_div(i - 1);
//cout << 1 / i << endl;
//nop();
}
catch (std::exception& e)
{
cout << "caught in try_div(" << i << "): " << e.what() << endl;
}
}
int main()
{
/* ... */
try
{
try_div(4);
}
catch (std::exception& e)
{
cout << "caught in main(): " << e.what() << endl;
}
}
edit: I have submitted this as a possible bug in gcc, and reduced my code to a simple test case.
It's been a while, but I finally figured it out... The throwing function needs to be marked as having a signal frame.
[[gnu::no_caller_saved_registers]]
void throw_exception()
{
asm(".cfi_signal_frame");
throw std::runtime_error("Division by zero!");
}
IN the below code snippet why is that if I include the catch statement with "exception base class I get a app crash" (attached the image of teh crash).
But if I use
"const char* msg"
in catch() it works fine.
WHy is it that the exception base class is causing teh app crash ?
double division(int a, int b)
{
if (b == 0)
{
throw "Division by zero condition!";
}
return (a / b);
}
main()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (const char* msg) { // WORKS FINE
//catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
Here you are throwing a string literal:
throw "Division by zero condition!";
Which can be caught with the following:
catch (const char* msg)
However this exception does not derive from the class std::exception. If you want one which is and can provide an error message then use std::runtime_error.
throw std::runtime_error("Division by zero condition!");
...
catch (std::exception& err)
Division by zero condition is not derived by std::exception
one workaround you can do is to define catch all statement in you code
try {
z = division(x, y);
cout << "after division func" << endl;
cout << z << endl;
}
catch (exception& err) { // CAUSES the APP to crash![enter image description here][1]
cout << "INside catch for divide by 0" << endl;
}
catch(...) //include this in your code
{
cout<<"other exception occured";
}
See here http://ideone.com/TLukAp