在观看在线教程并阅读之后,我很难理解异常处理。我试图通过测试驱动开发,我不能。到目前为止我想出的是这个。我应该使用这个结构
struct ArrayException
{
ArrayException(string newMessage = "error") :message(newMessage)
{
}
string message;
};
第一次尝试。
int sum(int* theArray, unsigned int arraySize)
{
try
{
if (theArray = NULL)
{
throw ArrayException("NULL ARRAY REFERENCE");
}
}
catch (int* param)
{
cout << "you can't have " << param << " as an array size";
}
int sum = 0;
for (int i = 1; i < arraySize; i++)
{
sum += theArray[i];
}
return sum;
}
我也尝试过这样做。
int sum(int* theArray, unsigned int arraySize)
{
if (theArray = NULL)
{
throw ArrayException("NULL ARRAY REFERENCE");
}
else
{
int sum = 0;
for (int i = 1; i < arraySize; i++)
{
sum += theArray[i];
}
return sum;
}
}
答案 0 :(得分:3)
虽然这篇文章没有特别提及,但我认为问题是为什么没有抓住异常?答案很简单 - 因为抛出的异常是ArrayException类型,而catch是使用int *类型完成的。
答案 1 :(得分:0)
掌握这些东西的最佳方法是推荐πάνταῥε:获得一本好书。这是开始选择书籍的好地方:The Definitive C++ Book Guide and List
其余的是带有注释的代码块,我认为它们是必需的。
#include <iostream>
// removed the using namespace std;
struct ArrayException
{
ArrayException(std::string newMessage = "error") :
message(newMessage)
{
}
std::string message;
};
int sum(int* theArray, size_t arraySize) // change made here:
// size_t better suited than unsigned int for indexes
{
//throw std::out_of_range("BOOM!"); //uncomment to trigger a std::exception
//throw 42; // uncomment to trigger the unknown exception
if (theArray == NULL)
{
throw ArrayException("NULL ARRAY REFERENCE"); //perfect!
}
else
{
int sum = 0;
for (size_t i = 0; i < arraySize; i++) // changes made here:
// size_t not int to get rid of signed/unsigned conflict
// starting with array index 0, not 1
{
sum += theArray[i];
}
return sum;
}
}
int main()
{
try
{
sum (NULL, 10); // NULL address to force the exception
}
catch (ArrayException & param) // catch the custom exception
// catch by reference where possible
{
std::cout << "This bad stuff happened: " << param.message << std::endl;
}
// extra stuff to show what can also be done
catch (std::exception & stdexcpt) // catch any standard exceptions and
// print their message
{
std::cout << "Standard exception thrown: " << stdexcpt.what() << std::endl;
}
catch (...) // catch anything else that was thrown and doesn't
// correspond to any expectation
{
std::cout << "No idea what happened." << std::endl;
}
}