Rethrowing exception

Question is in the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <stdexcept>

int main()
{
    bool flag = true;

    try {
       try {
          throw std::runtime_error("");
       } catch (std::exception const& inner_std_exception) {
          if (flag) {
             // goes to outter catch(std::exception const&)
             // QUESTION: why is this not caught by catch (std::runtime_error const&)?
             throw inner_std_exception;
          } else {
             // goes to catch (std::runtime_error const&)
             throw;
          }
       }
    } catch (std::runtime_error const& runtime_error) {
       std::cout << "caught std::runtime_error" << '\n';
    } catch (std::exception const& outter_std_exception) {
       std::cout << "caught std::exception" << '\n';
    }

    return 0;
}
Last edited on
Whenever you use throw expression;, a new object is created. And since the static type of inner_std_exception is std::exception that is the type you get. Whereas if you just use throw; you re-throw the current exception - nothing new is created.

If you're thinking that catch behaves like a function where throw is analogous to return - don't.
cire

Thank you for the explanation. Now I understand.
Topic archived. No new replies allowed.