C++ c++;::在c+中定义类时通过抛出catch给出异常+;?
我试图抛出异常C++ c++;::在c+中定义类时通过抛出catch给出异常+;?,c++,class,throw,C++,Class,Throw,我试图抛出异常 templete<typename t> class test{ . . . t test1(){ if(...){ throw "exception"; } else{ return(....); } } } 模板 课堂测试{ . . . t test1(){ 如果(…){ 抛出“异常”; } 否则{ 返回(……); } } } 然后在int main中尝试捕获 int main(){ try{
templete<typename t>
class test{
.
.
.
t test1(){
if(...){
throw "exception";
}
else{
return(....);
}
}
}
模板
课堂测试{
.
.
.
t test1(){
如果(…){
抛出“异常”;
}
否则{
返回(……);
}
}
}
然后在int main中尝试捕获
int main(){
try{
cout<<test1();
}
catch(const char *e){
cout<<e<<endl;
}
return 0;
}
t testresult(){
try{
if(...){
throw "exception";
}
else{
return(....);
}
}
catch(const char *e){
cout<<e<<endl;
}
}
intmain(){
试一试{
不能使用try-catch
int main(){
try{
cout<<test1();
}
catch(const char *e){
cout<<e<<endl;
}
return 0;
}
t testresult(){
try{
if(...){
throw "exception";
}
else{
return(....);
}
}
catch(const char *e){
cout<<e<<endl;
}
}
t测试结果(){
试一试{
如果(…){
抛出“异常”;
}
否则{
返回(……);
}
}
捕获(常量字符*e){
你可以抛出一个字符串但捕获一个字符。问题是你抛出一个const char*
并捕获一个const char
?也许你应该抛出std::runtime\u exception
或类似的东西。你的意思是在类test
的构造函数中尝试catch
?哦,请创建一个,并编辑您的问题以包含该问题,而不是您当前的(非编译)代码。请将try catch放在test1
中,也许?它会在异常后打印随机数或字符串或其他数据类型作为我的数据类型t。为什么不只是if(…){cout@dornhege它消除了try-catch的优点。它非常有用,因为它可以分离主代码和异常处理程序代码。假设else
块非常长,并且有更多的throw
s.@Dharmendra什么??嗯..你能给我什么?@ikh我正在给出示例代码[.它在代码::Blocks 13.12上运行良好,但它在异常后打印随机数。但我认为这是IDE特有的问题