【发布时间】:2014-10-01 20:54:58
【问题描述】:
我正在尝试抛出异常。
templete<typename t>
class test{
.
.
.
t test1(){
if(...){
throw "exception";
}
else{
return(....);
}
}
}
然后在 int main try-catch
int main(){
try{
cout<<test1();
}
catch(const char *e){
cout<<e<<endl;
}
return 0;
}
请建议我如何在类测试中使用 try-catch,这样我就不需要 int main。 正如评论者所建议的,我包括简单的代码
#include<iostream>
using namespace std;
template<typename t>
class test{
public:
t b;
test(){
cin>>b;
}
t testresult(t a){
if(b==a){
throw "Same";
}
a=b;
return a;
}
};
int main(){
try{
test<int> d;
int a;
cin>>a;
cout<<d.testresult(a);
return 0;}
catch(const char *e){
cout<<"exception_"<<e<<endl;
}
}
也尝试在 test1 中使用 try catch,但它打印整数或字符串等作为我的数据类型 t
【问题讨论】:
-
你抛出了一个字符串,但捕获了一个字符。
-
问题是你抛出
const char *并捕获const char?也许你应该抛出std::runtime_exception或类似的东西。 -
你的意思是
try-catch在类test的构造函数中? -
哦,请创建一个Minimal, Complete, and Verifiable example,并编辑您的问题以包含它而不是您当前的(非编译)代码。
-
把 try-catch 放在
test1里面,也许?