#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;
}
往往我们在使用try、catch函数时,会出现上述无法catch到对应throw的字符串是什么。见上图。
经过一段时间的思考,总算找出原因了。假如你在catch *char的前面加上一个const,那么catch就可以捕捉到前面的构造函数中throw的字符串了。如下图所示
更正后代码
#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;
}
注意
此外,这里还要注意一个很重要的问题,
就是当运行窗口显示下图时,千万不要直接关闭运行窗,否则会导致内存外溢,该程序无法再构建和运行了。会显示如下错误
Cannot open output file, permission denied
读者也可以进入上面的链接看看别人的解释。出现无法运行的上述错误后,需要等一段时间才可以继续运行,或者重新新建一个cpp,把复制粘贴过去。