0

After JAVA I had to tackle C ++. The simplest example, but it doesn’t work for me:

#include <iostream>

void handle_exceptions(std::exception_ptr e);

   std::exception_ptr e;   

int main()
{


    try {
        throw new std::exception("test");
    }
    catch (...) {
        e = std::current_exception();
        handle_exceptions(e);
    }
} // END: main

void handle_exceptions(std::exception_ptr e)
{

    try {

        if (e) { std::rethrow_exception(e); }

    }
    catch (const std::exception & e) {

        std::cerr << std::endl << e.what();
        std::exit(0);
    }
} // END: handle_exception()

The line of std::rethrow generates an unhandled exception: Возникло необработанное исключение по адресу 0x766A08B2 в ConsoleApplication1.exe: исключение Microsoft C++: std::exception по адресу памяти 0x00BAF1F0.

Possible std::exception_ptr is not NULL. Wrong memory access, but why?

Yury Finchenko
  • 1,035
  • 13
  • 19
  • 1
    Can you please (temporarily) change your language settings in Windows to English, and then rerun the program to get the error output in English? While some here understand Russin (I guess) it's a minority. – Some programmer dude Jan 22 '20 at 14:53
  • 2
    FWIW, `new` is not needed in `throw new std::exception("test");`. You can just use `throw std::exception("test");`. `new` should not really be used anymore in C++. – NathanOliver Jan 22 '20 at 14:54
  • https://en.cppreference.com/w/cpp/error/exception/exception I don't see any constructor taking `char*` or similiar – lars Jan 22 '20 at 14:54
  • @NathanOliver - But that would change the outcome ;) – StoryTeller - Unslander Monica Jan 22 '20 at 14:56
  • 3
    You're throwing an `exception*` but catching a `const exception&`, which will not work. (Also, you have a local variable `e` that shadows a parameter `e`, and both of them shadow a global variable `e`. This is very confusing.) – Raymond Chen Jan 22 '20 at 14:58
  • Won't compile https://gcc.godbolt.org/z/WARpXp – Aykhan Hagverdili Jan 22 '20 at 14:59
  • 1
    Google Translate: "An unhandled exception occurred at address 0x766A08B2 in ConsoleApplication1.exe: Microsoft C++ exception: std::exception at memory address 0x00BAF1F0." – user253751 Jan 22 '20 at 15:02
  • Java idioms and semantics are not the same as C++ idioms and semantics. You may have to unlearn some Java and learn how C++ does things. There is a selection of [good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Eljay Jan 22 '20 at 15:43

1 Answers1

2

Change

throw new std::exception("test");

to

throw std::exception("test");

By the way, std::exception("test") with "test" passed as an argument doesnt compile in my case with g++.

rjhcnf
  • 762
  • 6
  • 12