0

I need an explanation of what this code actually do, I can't really think of what I should specify to the search engine to find an answer to that, so I've decided to ask stackoverflow's community once again:

Let's say we have a function called means:

double means(double a, double b){
    double am, hm, gm;
    am = (a + b) / 2.0;   
    try
    {
        hm = hmean(a,b);
        gm = gmean(a,b);
    } 
    catch (bad_hmean & bg)
    {
        // do something
        throw;
    }
    return (am+hm+gm)/3.0;
}

And let's say function hmean inside try block does something that throws an exception which is a bad_hmean object. So the first catch block inside means function is triggered. It throws another exception, because of the line that contains throw;.

Now, our means functions was declared in for example, main function, in another try-catch block:

int main(){
    
    // variables, etc.
    
    try{
        means(a,b);
    }
    catch (bad_hmean & bg){
        // this catch block is being triggered
        // after means function throws the exception in it's catch block

        // block does something
    }
}

My question is - why is that, that in our function means, when it reads the line which contains just throw (in the catch block) without specifying the type of the exception, the catch in main is being triggered? How does the catch block in main know, which type of exception did means function throw? Is it that, that when we're declaring another throw in a catch block which already has been triggered by a certain type of variable - we don't need to specify the argument another time? How does it work?

todovvox
  • 170
  • 10
  • 1
    It rethrows the current exception. It's more useful in a catch-all block (`catch (...)`) where you don't have a reference to the caught object. – jamesdlin Mar 14 '22 at 00:28
  • Yes, you are right. Thank you very much, now I see.. Somebody correctly voted as a duplicate for this question. – todovvox Mar 14 '22 at 00:30

0 Answers0