【问题标题】:c++::giving exception through throw catch in defining class in c++?c++::在c++中定义类时通过throw catch给出异常?
【发布时间】: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 里面,也许?

标签: c++ class throw


【解决方案1】:

...只需使用 try-catch

t testresult(){
    try{
        if(...){
            throw "exception";
        }
        else{
            return(....);
        }
    }
    catch(const char *e){
        cout<<e<<endl;
    }
}

假设您在 your live example link 中的代码,不是您问题中的代码,这不是 IDE 的错误 - 这是 您的错

#include<iostream>
using namespace std;
template<typename t>
class test{
public:
    t b;
    test(){
        cin>>b;
    }
    t testresult(t a){
        try{
        if(b==a){
            throw "Same";
         }
         else{
            a=b;
            return a;
         }
         }
         catch(const char *e){
         cout<<"Exception_"<<e; // here
         }
    }
    };
int main(){
            test<int> d;
            int a;
            cin>>a;
            cout<<d.testresult(a);
            return 0;
}

看看// here。您必须返回 t 类型的任何值,但您没有


嗯,当涉及到您的代码时在您的问题中,您可能没有提供任何输入。 (某些 IDE 在运行程序之前需要它)

首先,查看normal case,提供输入。

再看另一种情况,没有提供任何输入。

【讨论】:

  • 它在异常后打印随机数或字符串或其他作为我的数据类型 t
  • 为什么不只是if(...) { cout &lt;&lt; "exception" &lt;&lt; end; } else { return ...' }
  • @dornhege 它消除了 try catch 的好处。它非常有用,因为它可以将主代码异常处理代码分开。假设else 块非常长并且有更多throws。
  • @Dharmendra 什么?嗯..你能给我mcve吗?
  • @ikh 我正在提供示例代码 [code.hackerearth.com/….它在 Code::Blocks 13.12 上运行良好,但它在 Exception 之后打印随机数。但我认为这是 IDE 特定问题
猜你喜欢
  • 2017-01-05
  • 2013-06-01
  • 2014-07-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 2021-08-24
  • 2019-05-20
  • 1970-01-01
相关资源
最近更新 更多