Catch a few parameters

First I found in cplusplus.com the following quote:

The catch format is like a regular function that always has at least one parameter.

But I tried this:

try
{
    int kk3,k4;
    kk3=3;
    k4=2;
    throw (kk3,"hello");
}
catch (int param)
{
    cout << "int exception"<<param<<endl;     
}
catch (int param,string s)
{
    cout<<param<<s;
}
catch (char param)
{
    cout << "char exception";
}
catch (...)
{
    cout << "default exception";
}

The compiler does not complain about throwing with curly brackets and several arguments. But in fact, he complains about a catch with several parameters, despite the fact that the link says. I'm confused. Do trythey have catchthis multiplicity or not? And what if I wanted to throw an exception that included more than one variable with or without the same type.

+3
source share
2 answers

(kk3, "hello" ) . , - . ,

int i = (1,3,4); 

i 4.

( - ),

 throw std::make_pair(kk3, std::string("hello")); 

:

catch(std::pair<int, std::string>& exc)
{
}

catch

...

+10

, . std::exception. , catch(std::exception&) (, - , - gazilion , ).

:

class MyException : public std::exception {
   int x;
   const char* y;

public:
   MyException(const char* msg, int x_, const char* y_) 
      : std::exception(msg)
      , x(x_)
      , y(y_) {
   }

   int GetX() const { return x; }
   const char* GetY() const { return y; }
};

...

try {
   throw MyException("Shit just hit the fan...", 1234, "Informational string");
} catch(MyException& ex) {
   LogAndShowMessage(ex.what());
   DoSomething(ex.GetX(), ex.GetY());
}
+2

Source: https://habr.com/ru/post/1771097/


All Articles