Re: Is exception specification available?
On Oct 12, 1:47 pm, vagrxie <v...@163.com> wrote:
#include <iostream>
#include <string>
using namespace std;
class c1
{
public:
c1()
{
c1str = "error 1";
}
string c1str;
};
class c2
{
public:
c2()
{
c2str = "error 2";
}
string c2str;
};
void fn() throw (c1,bad_exception)
{
cout<<"have problem"<<endl;
throw c2();
}
int main()
{
try
{
fn();
}
catch (const c2 &err)
{
cout << err.c2str <<endl;
}
catch (const bad_exception &)
{
cout << "catch bad_exception"<<endl;
}
catch (...)
{
cout << "catch another exception"<<endl;
}
cout <<"Done"<<endl;
return 0;
}
couldn't work well in VS 2005 as the books tell me,I tried DEV,It
couldn't work again.In the book(the C++ standard library)tell me,I
sould catch a bad_exception,why there were even no any exception throw?
On Visual Studio, if you didnt ignore the warnings, it would say
something like "fn -- Ignoring exceptios specification: exceptions
specifications not supported" and you should have seen 'have problem
error 2 Done' printed out.
On other compilers like Sun Workshop you would have see the program
aborted, because you are throwing a c2 throug a function that only
allows exceptions of type c1 and bad_exception to emit from it.
I dont know what book you are reading, but I dont think Josuttis' "The
C++ Standard Library" has many examples of working with throw
specifications. But I do know that many of the C++ books I have seen
get this part wrong. Books like "Exceptional C++" and "The C++
Programming Language" do get it right.
If you are just learningg C++ (or just exceptions) stay away from
throw specifications (that throw clause in the function declaration)
They are nothing like their Java counterparts. In fact they are
nothing but trouble. Just stick to making all of your exceptions
inherit from std::exception (in <stdexcept> and writing catch blocks
like
try{
//stuff that throws
}catch(std::exception const&e){
std::cerr<<e.what()<<std::endl;
}catch(...){
std::cerr<<"Caught Unknown Exception"<<std::endl;
}
This format will carry you throughout your entire career without all
the confusion.
Lance
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]