2017-07-12 73 views
1

我想在我的代碼中拋出一個異常,如果從用戶輸入創建的矢量未按降序或升序排序。C++異常沒有按預期方式處理

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; 
} 

}

我還沒有包括代碼,該代碼搜索一個特定號碼的休息,因爲我敢肯定,這是無關緊要的這個問題。當填充到向量中的數據是升序或降序時,一切都很好,但是當我測試異常時,我得到「在調用'char const *'Aborted」的實例後終止調用,而不是我想要的錯誤消息。我不明白這裏發生了什麼事。我處理異常的方式有問題嗎?或者我不正確地使用sort()函數?

+1

如果你交換'begin()'和'end()',你沒有得到一個向後的間隔,你會得到一個空的間隔。你想用'rbegin()'和'rend()'代替。 –

+0

在同一個塊中拋出並捕獲異常是沒有意義的。你應該用一個簡單的'if'來代替。 – Mattia72

+0

哇,這麼多括號!您可以將呼叫周圍的電話刪除到「is_sorted」 - 它們是多餘的。通過應用德摩根定理,你可以擺脫'if'語句中最外面的表達式:'!(A || B)'相當於'!A &&!B'。 –

回答

2

在C++中,所有類型都是可丟棄和可捕獲的,但是您只能捕獲std::exception的子類。

你的代碼的最好的解決將改變你的throw語句:

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

你投擲const char*不是std::exception。所以抓住它作爲const char*

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

或者拋出一個std::exception

請記住,你可以拋出許多類型和有很多catch塊,將被調用的是一個匹配的拋出異常的類型。

+0

小竅門。我不認爲'std :: exception'有一個構造函數,它可以吃一個字符串或類似的東西。 – user4581301