Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/152.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ c++;::在c+中定义类时通过抛出catch给出异常+;?_C++_Class_Throw - Fatal编程技术网

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特有的问题