![]() |
#2
rjsp2022-10-24 13:23
代码不全,但输出结果很正常呀,你捕获了 bootst::bad_lexical_cast 异常,然后又 throw 出去。外面没有捕获这个异常的代码,那按规定就应该直接调用 terminate()
你的代码逻辑我是看不懂 extern char *optarg; unsigned tryfunc(char *a) // 这个 a 没有用到,不知道是干什么的 { int intnum; // 返回类型是 unsigned,你定义个 int,不知道有什么深意 try { std::cout<<"ready to throw!\n"; if(!(intnum=boost::lexical_cast<unsigned>(optarg))) // 这里可能抛出 bootst::bad_lexical_cast 异常 throw (optarg); // 这里可能抛出 char* 异常 #如果有错不传到catch // 从什么现象能看出“如果有错不传到catch”? } catch(...) { exception e; // 这个就看不懂了,你不捕获别人给你的异常,而是自己定义一个? std::cout << "-------------------wrong: " << e.what(); throw; // 你throw的话,就应该保证有人catch,如果没有catch将调用terminate() } return intnum; } 我写了个测试代码 ![]() #include <iostream> #include <exception> #include "boost/lexical_cast.hpp" unsigned foo( const char* s ) { unsigned result = 0; try { result = boost::lexical_cast<unsigned>( s ); if( result == 0 ) throw s; } catch( const std::exception& e ) { std::cout << "-------------------wrong: " << e.what() << std::endl; throw; } catch( const char* s ) { std::cout << "-------------------wrong: " << s << std::endl; throw; } catch( ... ) { std::cout << "-------------------wrong: " << "other exception" << std::endl; throw; } return result; } using namespace std; int main( void ) { try{ cout << foo("123") << endl; } catch(...){} try{ cout << foo("abc") << endl; } catch(...){} try{ cout << foo("0") << endl; } catch(...){} try{ cout << foo("nullptr") << endl; } catch(...){} try{ cout << foo("123abc") << endl; } catch(...){} } 输出 123 -------------------wrong: bad lexical cast: source type value could not be interpreted as target -------------------wrong: 0 -------------------wrong: bad lexical cast: source type value could not be interpreted as target -------------------wrong: bad lexical cast: source type value could not be interpreted as target |
#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
已放弃