关于try catch
#include <iostream> //#include <fstream>
#include <exception>
#include <string>
#include "boost/lexical_cast.hpp"
#include <unistd.h>
using namespace std;
extern char *optarg;
unsigned tryfunc(char *a)
{
int intnum;
try {
std::cout<<"ready to throw!\n";
if(!(intnum=boost::lexical_cast<unsigned>(optarg)))
throw (optarg);
#如果有错不传到catch
}
catch(...)
{
exception e;
std::cout<<"-------------------wrong:"<<e.what();
throw ;
}
return intnum;
}
int main(int argc,char *argv[])
{
int opt,rmint=5;
string help="wrong!\n";
while ((opt = getopt(argc, argv, ":r:")) != -1)
{
switch (opt)
{
case 'r':
rmint=tryfunc(optarg);
break;
default: /* '?' */
std::cout<<help<<endl;
return 0;
}
}
std::cout<<"you input optarg:"<<rmint<<endl;
}
#以下是我的运行结果
wei@wei:~/bin$ ./mn -ra
ready to throw!
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
what(): bad lexical cast: source type value could not be interpreted as target
已放弃