【五一创作】C++异常处理报错【terminate called after throwing an instance of ‘char const‘】

 

#include<iostream>
using namespace std;
const int Maxsize=100;
template<class T>
class SeqList
{
public:
    SeqList();
    SeqList(T a[],int n);
    ~SeqList();
private:

    int length;
    T data[Maxsize];
};
template<class T>
SeqList<T>::SeqList(T a[],int n)
{
    if(n<Maxsize)
        throw "111";
    else
        cout<<"right";
    for (int i=0;i<n;i++)
        data[i]=a[i];
    length=n;
}
template<class T>
SeqList<T>::~SeqList()
{

}
int main()
{
    try
    {
        int   a[]={1,2,3,4,7,4};
        int n;
        cin>>n;
    SeqList<int> b(a,7);
    }
    catch(char *str)
    {
        cout<<str<<endl;
    }



    return 0;
}
#include<iostream>
using namespace std;
const int Maxsize=100;
template<class T>
class SeqList
{
public:
    SeqList();
    SeqList(T a[],int n);
    ~SeqList();
private:

    int length;
    T data[Maxsize];
};
template<class T>
SeqList<T>::SeqList(T a[],int n)
{
    if(n<Maxsize)
        throw "111";
    else
        cout<<"right";
    for (int i=0;i<n;i++)
        data[i]=a[i];
    length=n;
}
template<class T>
SeqList<T>::~SeqList()
{

}
int main()
{
    try
    {
        int   a[]={1,2,3,4,7,4};
        int n;
        cin>>n;
    SeqList<int> b(a,7);
    }
    catch(char *str)
    {
        cout<<str<<endl;
    }



    return 0;
}

646dadb6c2fe4ea49538cf70ffb3ec36.png

往往我们在使用try、catch函数时,会出现上述无法catch到对应throw的字符串是什么。见上图。

经过一段时间的思考,总算找出原因了。假如你在catch *char的前面加上一个const,那么catch就可以捕捉到前面的构造函数中throw的字符串了。如下图所示

03d6a0186e18493e922cbf18bc84aa8c.png

 更正后代码

#include<iostream>
using namespace std;
const int Maxsize=100;
template<class T>
class SeqList
{
public:
    SeqList();
    SeqList(T a[],int n);
    ~SeqList();
private:

    int length;
    T data[Maxsize];
};
template<class T>
SeqList<T>::SeqList(T a[],int n)
{
    if(n<Maxsize)
        throw "111";
    else
        cout<<"right";
    for (int i=0;i<n;i++)
        data[i]=a[i];
    length=n;
}
template<class T>
SeqList<T>::~SeqList()
{

}
int main()
{
    try
    {
        int   a[]={1,2,3,4,7,4};
        int n;
        cin>>n;
    SeqList<int> b(a,7);
    }
    catch(const char *str)
    {
        cout<<str<<endl;
    }
    return 0;
}

注意

此外,这里还要注意一个很重要的问题,

就是当运行窗口显示下图时,千万不要直接关闭运行窗,否则会导致内存外溢,该程序无法再构建和运行了。会显示如下错误

2b398e9e0a7b43d6afc5f1c6ce0682b8.png

 Cannot open output file, permission denied

读者也可以进入上面的链接看看别人的解释。出现无法运行的上述错误后,需要等一段时间才可以继续运行,或者重新新建一个cpp,把复制粘贴过去。

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牛哥带你学代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值