C++ 异常未按预期处理

C++ exception not handling as expected

如果根据用户输入创建的矢量未按降序或升序排序,我将尝试在我的代码中抛出异常。

using namespace std;
#include <iostream>
#include <vector>
#include <algorithm>

int main () {
vector <int> vec;

//Let user fill a vector with 12 integers.
//cout << "Please note that input data should be either increasing or decreasing." << endl;
int n = 0;
int size = 0;
while(size < 12) {
    cout << "Type integer to add to the vector." << endl;
    cin >> n;
    vec.push_back(n);
    ++size;
}

//throw exception if unsorted
try {
    if (!((is_sorted(vec.begin(), vec.end())) || (is_sorted(vec.end(), vec.begin())))) {
        throw "Input was not sorted.";
    }
}
catch(exception &error){
    cerr << "Error: " << error.what() << endl;
}

}

我没有包括搜索特定号码的其余代码,因为我很确定它与这个问题无关。当填充到向量中的数据是升序或降序时,一切都很好,但是当我测试异常时,我得到 "terminate called after throwing an instance of 'char const*' Aborted" 而不是我想要的错误消息。我不明白这是怎么回事。是我处理异常的方式有问题还是我错误地使用了 sort() 函数?

你扔的是 const char* 而不是 std::exception。所以将其捕获为 const char*:

  catch(const char* error) {
    std::cout << "Error: " << error << "\n";
  }

或者抛出一个std::exception.

请记住,您 可以 抛出许多类型并且有许多 catch 块,将被调用的是与抛出的异常类型匹配的块。

在 C++ 中,所有类型都是可抛出和可捕获的,但您只能捕获 std::exception 的子类。

对代码的最佳修复是将 throw 语句更改为:

throw std::runtime_error("Input was not sorted.");

如果你想捕获异常,你应该抛出一个异常,而不是const char*。 看到这个答案:c++ exception : throwing std::string