I had this fun idea last night to catch the hardware exceptions and throw it away instead C++ exception. Thought it could be useful for things like FPU exceptionsthat usually either crash or silently return NaN, and then cause unexpected behavior. A C++ exceptionwould be much more desirable here.
So, I hacked all morning and finally got it to work. Almost. The compiler still does not understand that arithmetic operations can now be discarded C++ exceptionsand will silently discard a block around it try/catch. It works when an 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()
{
exception_wrapper div0_exc { 0, [] (exception_frame* frame, bool)
{
if (frame->address.segment != get_cs()) return false;
frame->stack.offset -= 4;
auto* stack = reinterpret_cast<std::uintptr_t *>(frame->stack.offset);
*stack = frame->address.offset;
frame->address.offset = reinterpret_cast<std::uintptr_t>(throw_exception);
return true;
} };
try
{
try_div0();
}
catch (std::exception& e)
{
cout << "oops: " << e.what() << endl;
}
}
, ... ? gcc, ?
djgpp, ( ) DWARF .
edit: gcc flags -fnon-call-exceptions -fasynchronous-unwind-tables, , , . ...
edit: , gcc, , :
inline void nop() { asm(""); }
int main()
{
try
{
nop();
cout << 1 / 0 << endl;
nop();
}
}
edit: try/catch , , .
inline void nop() { asm(""); }
void try_div(int i)
{
try
{
nop();
cout << 1 / i << endl;
try_div(i - 1);
}
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: gcc .