Paul
unread,Nov 20, 2015, 8:35:53 AM11/20/15You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
I was trying to test a very basic example of exception handling but instead I got an ugly crash with a message that the application "requested the Runtime to terminate in an unusual way."
I'd be grateful if anyone could explain why the exception is not being handled correctly. The complete code is included below. The what() is what I hoped -- "Vector too long" but (my implementation of) the try/catch/throw basic methodology seems to be awry.
Thank you,
Paul
/* Converting a sorted vector
into a binary search tree.
Besides being sorted, the vector
elements are assumed to be unique */
#include <iostream>
#include <vector>
#include <cstdlib>
#include <stdexcept>
#include <set>
#include <algorithm>
#include <utility>
// Generating a random vector of a given length with no duplicates
std::vector<int> random(unsigned length)
{
if(!length)
return {};
const int maxLength = 30 * 1000;
if(length > maxLength)
throw std::runtime_error("Vector too long");
std::set<int> nonDuplicates;
int former;
std::pair<std::set<int>::iterator, bool>insertion;
std::vector<int> result;
for(int i = 0; i < length; ++i)
do
{
former = std::rand();
insertion = nonDuplicates.insert(former);
}
while(!insertion.second); // Assuring no duplicates
std::copy(nonDuplicates.begin(), nonDuplicates.end(), std::back_inserter(result));
if(result.size() != length)
throw std::runtime_error("Programmer error -- vector is the wrong size");
for(int i = 1; i < result.size(); ++i)
if(result[i] <= result[i-1])
throw std::runtime_error("Programmer error -- not sorted");
return result;
}
struct BST{
BST(int Val):left(nullptr), right(nullptr), val(Val)
{
}
BST* left;
BST* right;
int val;
};
BST* convertToBST(const std::vector<int>& sorted)
{
if(sorted.empty())
return nullptr;
if(sorted.size() == 1)
return new BST(sorted[0]);
const int midIndex = sorted.size()/2;
const int midpoint = sorted[midIndex];
const std::vector<int> left(sorted.begin(), sorted.begin() + midIndex);
const std::vector<int> right(sorted.begin() + midIndex + 1, sorted.end());
BST* result = new BST(midpoint);
result->left = convertToBST(left);
result->right = convertToBST(right);
return result;
}
void printTree(BST* const& tree)
{
if(tree)
{
printTree(tree->left);
std::cout << tree->val << std::endl;
printTree(tree->right);
}
}
int main()
{
// Test that large vectors are correctly generated
std::vector <int> test = random(30 * 1000);
for(int i = 0; i < 2; ++i)
{
std::vector <int> treeVec = random(!i ? 100 : 30 * 1000 + 1);
try
{
printTree(convertToBST(treeVec));
}
catch(std::runtime_error& e)
{
std::cout << e.what();
}
}
}