如何在类数组中的运算符 [] 中捕获异常
How to catch an Exception in operator[] in class Array?
我必须试一试...捕获此函数,但我不知道如何继续该程序:通过显示 a[size] 在捕获异常后显示数组。
请帮助我。
对不起,我的英语不好。
这是我的程序...非常感谢。。。
#include <iostream>
using namespace std;
namespace arr{
template<class T>
class Array{
private:
int size;
T* a;
public:
Array<T>();
Array<T>(int max);
~Array<T>();
T& operator[](int index) throw(int);
T& operator=(const T& a2);
void set(int index, T val);
void Display();
int GetSize();
void Sort();
T Max();
};
}
using namespace arr;
template<class T>
Array<T>::Array(){
size=0;
a=new T[0];
}
template<class T>
Array<T>::Array(int max){
size=max;
a=new T[size];
}
template<class T>
Array<T>::~Array(){
size=0;
delete[] a;
}
template<class T>
T& Array<T>::operator[](int index) throw(int){
try{
if(index>=0 && index <size)
return a[index];
else
throw(index);
} catch(int e){
cout<<"Exception Occured: ";
if(e<0)
cout<<"index < 0n";
else
cout<<"index >= "<<size<<endl;
exit(1);
}
}
template<class T>
T& Array<T>::operator=(const T& a2){
for(int i=0;i<a2.GetSize();i++) set(i,a2[i]);
return *this;
}
template<class T>
void Array<T>::set(int index, T val){
a[index]=val;
}
template<class T>
void Array<T>::Display(){
for(int i=0;i<size;i++)
cout<<a[i]<<" ";
cout<<endl;
}
template<class T>
int Array<T>::GetSize(){
return size;
}
template<class T>
void Array<T>::Sort(){
for(int i=0;i<size-1;i++)
for(int j=i+1;j<size;j++)
if(a[i]>a[j]){
T tmp=a[i];
a[i]=a[j];
a[j]=tmp;
}
}
template<class T>
T Array<T>::Max(){
T m=a[0];
for(int i=1;i<size;i++)
if(a[i]>m) m=a[i];
return m;
}
int main(){
int size=0;
cout<<"Size of Array: ";
cin>>size;
Array<int> a(size);
for(int i=0;i<size;i++){
int tmp;
cout<<"a["<<i+1<<"]=";
cin>>tmp;
a.set(i,tmp);
}
cout<<a[size]<<endl; //Test Exception.
cout<<"Your Array:n";
a.Display();
return 0;
}
当你有一个声明为的函数时:
T& operator[](int index) throw(int);
预计会引发异常。不需要有一个 try
/catch
块来抛出异常并处理异常。
您的实现可以是:
template<class T>
T& Array<T>::operator[](int index) throw(int){
// Check whether the index is valid.
// If it is not, throw an exception.
if(index < 0 || index >= size)
throw index;
// The index is valid. Return a reference
// to the element of the array.
return a[index];
}
该功能的用户将被要求使用try
/catch
块。
Array<int> a;
try
{
int e = a[5]; // This call will throw an exception.
}
catch (int index)
{
// Deal with out of bounds index.
}
相关文章:
- 当类定义不可见时捕获异常
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 如何通过 pybind11 从 python 中的C++中捕获异常?
- 信号后未捕获异常
- 捕获异常后如何退出程序执行
- C++ 捕获异常后进行清理的标准方法是什么?
- 使用模板类引发和捕获异常
- E/libc++abi:终止于类型为google::protobuf::FatalException的未捕获异常
- 如果在生成 std::thread 后引发,则未捕获异常
- C++ 未捕获异常,程序将终止并中止
- C++程序在第一次尝试时会给出垃圾,但如果它捕获异常并重试,则会给出适当的值
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如何捕获 I/O 异常(确切地说是 I/O,而不是 std::exception)
- 为什么捕获异常播放允许尾括号
- throw() 函数应该总是在异常时展开堆栈并允许捕获异常还是必须调用 std::terminate ?
- 寻求与类型为 std::invalid_argument 的未捕获异常相关的运行时错误的建议: stoi:无转换
- 如何从调用函数中捕获异常
- 当用户在字符数组中输入整数值时捕获异常
- C++按值捕获异常时的示例是不好的
- 如何在类数组中的运算符 [] 中捕获异常