Reputation: 409
I'm trying to throw an exception in my code if a vector that is created from user input is not sorted in either descending or ascending order.
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;
}
}
I have not included the rest of the code, which searches for a particular number, because I am pretty sure that it is irrelevant to this issue. When the data filled into the vector is ascending or descending, everything is fine, but when I test the exception, I get, "terminate called after throwing an instance of 'char const*' Aborted" instead of my desired error message. I don't understand what is going on here. Is it something wrong with the way I'm handling exceptions or am I using the sort() function incorrectly?
Upvotes: 1
Views: 124
Reputation: 29332
You're throwing a const char*
not an std::exception
. So catch it as a const char*
:
catch(const char* error) {
std::cout << "Error: " << error << "\n";
}
Or throw an std::exception
.
Remember that you can throw many types and have many catch
blocks, the one that will be invoked is the one that matches the type of the thrown exception.
Upvotes: 0
Reputation: 1169
If you want to catch an exception, you should throw an exception, not a const char*
.
See this answer: c++ exception : throwing std::string
Upvotes: 0
Reputation:
In C++, all types are throwable and catchable, but you are only catching subclasses of std::exception
.
The best fix to your code would be changing your throw statement to:
throw std::runtime_error("Input was not sorted.");
Upvotes: 2