testing "Try and Catch" - c++

In this program, I am using template class, I have a header file and this is my main file. I am having trouble displaying the (".....") IndexOutOfBounds and displaying it on the screen.
#include "XArray.h"
#include <iomanip>
#include <string>
using namespace std;
template<class T>
void afriend ( XArray<T> );
int main()
{
XArray<double> myAD(18);
myAD.randGen(15, 100);
cout << myAD.getType() << endl;
cout << setprecision(1) << fixed << "\n\n Unsorted: " << myAD;
myAD.sort();
cout << "\n Now Sorted: " << myAD;
cout << "\n\n";
**try
{
cout << "A[-5] = " << setw(6) << myAD[-5] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
e.print();
}
try
{
cout << "A[8] = " << setw(6) << myAD[8] << endl;
}
catch(XArray<double>::IndexOutOfBound e)
{
e.print();
}**
cout << "\n\n" << setprecision(2) << fixed;
cout << "Size = " << setw(6) << myAD.getSize() << endl;
cout << "Mean = " << setw(6) << myAD.mean() << endl;
cout << "Median = " << setw(6) << myAD.median() << endl;
cout << "STD = " << setw(6) << myAD.std() << endl;
cout << "Min # = " << setw(6) << myAD.min() << endl;
cout << "Max # = " << setw(6) << myAD.max() << endl;
return 0;
}
There is the Array.h file posted as a dropbox link
Array.h
The code for operator[] in Array.h is:
template <class T>
T XArray<T>::operator[] (int idx)
{
if( (idx = 0) && (idx < size) )
{
return Array[idx];
}
else
{
throw IndexOutOfBound();
return numeric_limits<T>::epsilon();
}
}

Although the question is somewhat obscure, give a try to these suggestions.
Firstly, it can happen that XArray<>::IndexOutOfBounds have no proper copy ctor. You can try catching by const reference to workaround that:
try
{
...
}
catch(const XArray<double>::IndexOutOfBound& e)
{
e.print();
}
Index operator in standard library containers does not check for bounds, there is a special getter that does the check called at(). If the XArray class is designed with standard library in mind, it could behave similarly.
However to get more adequate response you need to be more specific describing the trouble you are having.

I'm still wondering what exact question is.
However, I'm understanding the question is that how I can use 'catch' by using 'IndexOutOfBound'.
#include <exception>
#include <iostream>
using namespace std;
template <typename T>
class Array
{
private:
int m_nLength;
T *m_ptData;
public:
...
...
T& operator[](int nIndex)
{
//assert(nIndex >= 0 && nIndex < m_nLength);
if(nIndex < 0 || nIndex > m_nLength)
{
throw myex;
}
else
{
return m_ptData[nIndex];
}
}
//class definition for 'IndexOutOfBound'
class IndexOutOfBound: public exception
{
public:
virtual const char* print() const throw()
{
return "Exception occured 'Index Out Of Bound'";
}
}myex;
};
int main()
{
Array<double> arr(3);
try
{
arr[0] = 1;
//exception will occur here.
arr[4] = 2;
}
catch(Array<double>::IndexOutOfBound &e)
{
cout << e.print() << '\n';
}
return 0;
}
Here is no 'XArray.h', so I've written a sample array class for example.

The problem is in the operator[] function. The code idx = 0 sets idx to 0. So all of your calls to operator[] will return the first element, and therefore there is no out-of-bounds error unless the array is empty.
You probably meant to write if ( idx >= 0 && idx < size ).
BTW the throw aborts the function, it makes no sense to return after throw.

Related

How do I only display the first 10 elements of a Vector using an Iterator?

I'm trying to use displayVectorVer2() to have it only display the first 10 elements, but I don't know how to do it with iterators. I did try a few dumb things just to see what would happen: I compared the iterator to displayLimit in my for loop. I played around by subtracting vobj.end()-5 since my professor is only having me use 15 elements, but I fully well knew this was not a good idea.
#include <iostream>
#include <vector>
#include <ctime>
template <class T>
void fillVector(std::vector<T>& vobj, int n);
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr);
template <class T>
void fillVector(std::vector<T>& vobj, int n)
{
srand((unsigned int)time(NULL));
for (int i=0; i<n; ++i)
{
vobj.push_back(rand()%99999+1);
}
}
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr)
{
std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << std::endl;
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Before calling fillVector(...): vobj contains "
<< vobj.size() << " values." << std::endl;
std::cout << "\nEnter # of random values you'd like to store in vobj: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj, n);
std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
std::vector<int>::iterator ptr;
displayVectorVer2(vobj,ptr);
}
Maybe I am thinking too simple but, that wold solve your question:
I'm trying to use displayVectorVer2() to have it only display the
first 10 elements
without knowing your full exercise, that would be my answer:
...
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
for (ptr=vobj.begin(); ptr<vobj.begin()+displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
...
edit:
That worked, but why does it work? I remember adding to vobj.begin() and getting extra empty elements appended to the original vector.
Not sure what exactly you did but maybe that helps you understanding your code:
...
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
//Init ptr outside the for loop
ptr = vobj.begin();
//What the for loop is seeing with a more familiar syntax:
//for( ; i < 0 +displayLimit; ++i)
//what you are seeing
for (/*ptr init*/; ptr < vobj.begin() +displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
...
The iterators just gives you the int value and you can use it with what ever "eats" int values. In your case the for loop.
If you tell the program to use an iterator you tell the program: "Just give me the number the Vector begins with and add 10".
In your case 0 "...and add 10"
You could also write a code like that with n passed to the function
for being able to use .end - input + 10 for showing 10 lines:
...
template <class T>
void displayVectorVer2(std::vector<T>& vobj, typename std::vector<T>::iterator ptr,int n)
{
std::cout << "Vector object contains " << vobj.size() << " values which are" << std::endl;
const unsigned displayLimit = 10;
if (vobj.size()>displayLimit)
{
ptr=vobj.begin();
for (; ptr<vobj.end() -n +displayLimit; ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << " ..." << std::endl;
}
else
{
for (ptr=vobj.begin(); ptr<vobj.end(); ++ptr)
{
std::cout << " " << *ptr;
}
std::cout << std::endl;
}
}
int main()
{
std::vector<int> vobj;
std::cout << "Before calling fillVector(...): vobj contains "
<< vobj.size() << " values." << std::endl;
std::cout << "\nEnter # of random values you'd like to store in vobj: ";
int n;
std::cin >> n;
std::cout << "\n*** Calling fillVector(...) ***" << std::endl;
fillVector(vobj, n);
std::cout << "\n*** Calling displayVectorVer2(...) ***" << std::endl;
std::vector<int>::iterator ptr;
displayVectorVer2(vobj,ptr,n);
}
...
You also shouldn't use srand in modern code anymore since it is depricated for more than 10 years since c++11 introduced <random>
and srand can harm your program f.e. if used for generating seeds for sensitive code. Also srand provides not the "randomness" it should provide, srand generates some numbers more often than others - that's not random.

vector<string> in a struct doesn't work properly

I declared a vector<string> and I cannot even compile it. I tried many ways but none of them worked.
I'm trying to write out the x.surname.push_back(word)[i] but it's definetly written wrongly and I have no idea how to write it properly and make it possible to compile.
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int number, i = 0;
string word;
struct donators {
vector<string> surname;
vector<int> amount;
} x;
cout << "How many donators do you want to register? " << endl;
cin >> number;
for (i = 0; i < number; i++) {
cout << "Surname: ";
cin >> word;
x.surname.push_back(word)[i];
cout << "Amount: ";
x.amount.push_back(i);
cin >> x.amount[i];
}
cout << "OUR GORGEUS DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] >= 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
}
else if (x.amount[i] < 10000) {
cout << "Lack of surnames!" << endl;
}
}
cout << "OUR CASUAL DONATORS: " << endl;
for (i = 0; i < number; i++) {
if (x.amount[i] < 10000) {
cout << "Surname: " << x.surname(word)[i];
cout << "Amount: " << x.amount[i] << endl;
} else if (x.amount[i] >= 10000) {
cout << "Lack of surnames!" << endl;
}
}
return 0;
}
And one more thing. How to make sentence "Lack of surnames!" to be written out once? In some cases, it is written out twice or more times what is redundant.
You are putting [i] at seemingly random places in your code. Such as in x.surname.push_back(word)[i];. Don't add things like this to your code if you're unsure about what they're doing.
The x.surname(word)[i] construct are also wrong. What's x.surname(word) supposed to be? This syntax is for function calls. surname, however, is not a function. It's a std::vector<std::string>. Just put x.surname[i] instead.
And one more thing. How to make sentence "Lack of surnames!" to be
written out once? In some cases, it is written out twice or more times
what is redundant.
That's because you write it for every donor that doesn't fit the criterion. Instead, keep track if any donor fits the criterion and only print it when none ends up fitting. You can do it like this:
bool HasGorgeousDonators = false;
And then in the loop:
if (x.amount[i] >= 10000)
{
cout << "Surname: " << x.surname[i];
cout << "Amount: " << x.amount[i] << endl;
HasGorgeousDonators = true;
}
And after the loop:
if (!HasGorgeousDonators)
cout << "Lack of surnames!" << endl;
Likewise for the other loop. Also, please consider the following Q&A:
Why is "using namespace std;" considered bad practice?
It seems like you are writing C with some C++ help functions. However C++ is a different language. Sure, it supports some C structures, but there's so much more.
Take a look at some of my suggestions for implementation and compare it to your code:
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
template<typename T>
T ReadCin(std::string_view const& sv = "") {
T retVal;
if (!sv.empty()) std::cout << sv;
std::cin >> retVal;
return retVal;
}
class Donator {
private:
std::string surname{};
int amount{};
public:
constexpr bool IsGenerous() const noexcept { return amount >= 10000; }
void Read() noexcept {
surname = ReadCin<decltype(surname)>("Surname: ");
amount = ReadCin<decltype(amount)>("Amount: ");
}
friend std::ostream& operator<<(std::ostream& out, Donator const& donator) noexcept {
out << "Surname: " << donator.surname << ", " << "Amount: " << donator.amount;
return out;
}
};
int main() {
std::vector<Donator> donators(ReadCin<int>("How many donators do you want to register?\n"));
for (auto& donator : donators) donator.Read();
std::cout << "OUR GENEROUS DONATORS:\n";
std::copy_if(std::cbegin(donators), std::cend(donators), std::ostream_iterator<Donator>(std::cout, "\n"),
[](Donator const& donator) { return donator.IsGenerous(); });
std::cout << "OUR CASUAL DONATORS:\n";
for (auto const& donator : donators) if (!donator.IsGenerous()) std::cout << donator << '\n'; //alternative
}
I tried to include some of the possibilities using C++. I would really advise you to get a good book on C++.

How do I make an externally defined function available in a C++ class?

I have a class that I use with the Armadillo package to create a specific kind of matrix. I'm having trouble debugging it, so I would like to use a function I have written called Matlab_Print. It lives in its own .h and .cpp file and is used throughout my code. The class and the function both work perfectly, but I do not seem to be able to combine them.
I have tried #include "Matlab_Print" in SU3.h both before and after the class definition. I really don't want to make the function a class function as I use Matlab_Print frequently. I do have a workaround but it is inconvenient, and at any rate I am looking at this as a learning opportunity.
I trap error messages with a try when calling the SU3 constructor and I get the following:
error: Mat::init(): size is fixed and hence cannot be changed
main.cpp
#include "pch.h"
#include <new>
#include <exception>
#include "SU3.h"
int main(int argc, char *argv[])
{
int icount { 0 };
SU3 *su3[10];
try
{
for (icount = 0; icount < 10; icount++)
{
su3[icount] = new SU3(0.1);
}
}
catch (int param) { cout << "Function " << __func__ << " int " << param << " exception in memory allocation for su3" << std::endl; exit(1); }
catch (char param) { cout << "Function " << __func__ << " char " << param << " exception in memory allocation for su3" << std::endl; exit(1); }
catch (...) { cout << "Function " << __func__ << " exception in memory allocation for su3" << std::endl; exit(1); }
return 0;
}
SU3.h
#include "pch.h"
#include "SU3.h"
#include <armadillo>
#include "Matlab_Print.h"
class SU3
{
public:
arma::Mat<cx_double>::fixed<3, 3> *X;
SU3(const double epsilon);
};
SU3.cpp
SU3::SU3(const double epsilon) // simplifed so that epsilon plays no role
{
const std::complex<double> o{ 1.0 , 0.0 }; // complex 1
const std::complex<double> z{ 0.0 , 1.0 }; // complex 0
X = new arma::Mat<cx_double>::fixed<3, 3>{ fill::zeros }; //// solution to problem: define and initialize pointer ////
*X = { { o, z, z},
{ z, o, z},
{ z, z, o} };
Matlab_Print(*X, "SU3"); // this is the line I wish to use
}
Matlab_Print.h
#include <armadillo>
#include <complex>
void Matlab_Print(arma::Mat<cx_double>::fixed<3, 3> Matrix, std::string T);
Matlab_Print.cpp
#include "pch.h"
#include "Matlab_Print.h"
void Matlab_Print(arma::Mat<cx_double>::fixed<3, 3> Matrix, std::string T)
{
std::cout << std::endl;
std::cout << "RE = [" << std::real(Matrix(0, 0)) << " " << std::real(Matrix(0, 1)) << " " << std::real(Matrix(0, 2)) << "; ";
std::cout << std::real(Matrix(1, 0)) << " " << std::real(Matrix(1, 1)) << " " << std::real(Matrix(1, 2)) << "; ";
std::cout << std::real(Matrix(2, 0)) << " " << std::real(Matrix(2, 1)) << " " << std::real(Matrix(2, 2)) << "]; " << std::endl;
std::cout << "IM = [" << std::imag(Matrix(0, 0)) << " " << std::imag(Matrix(0, 1)) << " " << std::imag(Matrix(0, 2)) << "; ";
std::cout << std::imag(Matrix(1, 0)) << " " << std::imag(Matrix(1, 1)) << " " << std::imag(Matrix(1, 2)) << "; ";
std::cout << std::imag(Matrix(2, 0)) << " " << std::imag(Matrix(2, 1)) << " " << std::imag(Matrix(2, 2)) << "]; " << std::endl;
std::cout << T << " = RE + 1i*IM;" << std::endl;
}
Thank you for your patience. I hope this is all of the information you need.
As #uneven_mark notes, you have undefined behavior in SU3::SU3, because you are dereferencing X without initializing it first. You probably don't want a pointer here.
N.b. you don't need new to create objects of class type.
class SU3
{
public:
arma::Mat<cx_double>::fixed<3, 3> X;
SU3(const double epsilon);
};
using namespace std::literals::complex_literals;
SU3::SU3(const double epsilon)
: X({ { 1, 1i, 1i },
{ 1i, 1, 1i },
{ 1i, 1i, 1 } }) // prefer member initialisers over assingments
{
Matlab_Print(X, "SU3");
}

Giving one class Access to another C++

I am trying to access a member of one class in another class. I am fairly new to C++ so forgive me if this is an easy fix but I cannot find the answer, so I came here.
In this instance I would like to call "init();" from class CGuessNumber and member CheckNumber.
Here is my code.
#include <iostream>
#include <ctime>
#include <cstdlib>
class CGuessNumber
{
public:
int GenerateNumber()
{
return rand() % 100 + 1;
}
void checkNumber(int guess, int answer, int &attempts)
{
if (guess < answer)
{
std::cout << "TOO LOW, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess > answer)
{
std::cout << "TOO HIGH, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess == answer)
{
std::cout << "YOU WON!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}
if (attempts <= 0)
{
std::cout << "YOU LOST!" << "\n" << "TRYS LEFT: " << attempts << "\n";
CGAME::init(answer, attempts);
}
}
}Number;
class CGAME
{
public:
void init(int &answer, int &attempts)
{
answer = Number.GenerateNumber();
attempts = 5;
};
int newGame()
{
srand (time(NULL));
int intAnswer, playerGuess, trys;
init(intAnswer, trys);
while(intAnswer != playerGuess and trys > 0)
{
std::cin >> playerGuess;
Number.checkNumber(playerGuess, intAnswer, trys);
}
};
}ONewGame;
int main()
{
CGAME ONewGame
ONewGame.newGame();
return 0;
}
I think, this is what you're looking for
Basically you can pass a pointer which points to one object into a constructor of the other. In this case we just pass a pointer to CGuessNumber into the CGAME constructor, we also store this pointer in a private field so we can use it. Then you can use this pointer to call methods.
working example (pointer->method syntax)
working example (reference.method syntax)
#include <iostream>
#include <ctime>
#include <cstdlib>
class CGuessNumber
{
public:
int GenerateNumber()
{
return rand() % 100 + 1;
}
void checkNumber(int guess, int answer, int &attempts)
{
if (guess < answer)
{
std::cout << "TOO LOW, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess > answer)
{
std::cout << "TOO HIGH, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess == answer)
{
std::cout << "YOU WON!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}
if (attempts <= 0)
{
std::cout << "YOU LOST!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}
}
};
class CGAME
{
public:
CGAME(CGuessNumber* pNumber)
{
m_number = pNumber;
}
void init(int &answer, int &attempts)
{
answer = m_number->GenerateNumber();
attempts = 5;
};
void newGame()
{
srand (time(NULL));
int intAnswer, playerGuess, trys;
init(intAnswer, trys);
while(intAnswer != playerGuess and trys > 0)
{
std::cin >> playerGuess;
m_number->checkNumber(playerGuess, intAnswer, trys);
}
};
private:
CGuessNumber* m_number;
};
int main()
{
CGuessNumber* pGnum = new CGuessNumber();
CGAME* ONewGame = new CGAME(pGnum);
ONewGame->newGame();
return 0;
}
Let me just address the syntax errors.
In the checkNumber() function:
...
CGAME::init(answer, attempts);
...
There are 2 problems with this:
CGAME is not declared yet, so the compiler doesn't know it exists, or what it is. To avoid this, usually all the classes are declared at the top (or in a header file) and all there functions are defined later.
You can't call a member function of a class without an object, unless it's a static function. This function can be static as it doesn't use member variables (there are design issues, but lets ignore them for now).
Also in main() you missed a ';', but I think you already know that :-)
So, applying these changes:
#include <iostream>
#include <ctime>
#include <cstdlib>
// only declaring the classes here
class CGAME
{
public:
static void init(int &answer, int &attempts);
int newGame();
}ONewGame;
class CGuessNumber
{
public:
int GenerateNumber();
void checkNumber(int guess, int answer, int &attempts);
}Number;
// defining all the class member functions now
int CGAME::newGame()
{
srand (time(NULL));
int intAnswer, playerGuess, trys;
init(intAnswer, trys);
while(intAnswer != playerGuess and trys > 0)
{
std::cin >> playerGuess;
Number.checkNumber(playerGuess, intAnswer, trys);
}
}
int CGuessNumber::GenerateNumber()
{
return rand() % 100 + 1;
}
void CGuessNumber::checkNumber(int guess, int answer, int &attempts)
{
if (guess < answer)
{
std::cout << "TOO LOW, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess > answer)
{
std::cout << "TOO HIGH, TRY AGAIN" << "\n" << "TRYS LEFT: " << attempts << "\n";
attempts--;
}else if(guess == answer)
{
std::cout << "YOU WON!" << "\n" << "TRYS LEFT: " << attempts << "\n";
}
if (attempts <= 0)
{
std::cout << "YOU LOST!" << "\n" << "TRYS LEFT: " << attempts << "\n";
CGAME::init(answer, attempts);
}
}
void CGAME::init(int &answer, int &attempts)
{
answer = Number.GenerateNumber();
attempts = 5;
}
int main()
{
CGAME ONewGame;
ONewGame.newGame();
return 0;
}

how to use exceptions and pointers in a vector class

I have this vector class, and I was provided with a driver to test the class. Most of it seems to work fine but I think there is something wrong with the exceptions part (which I haven't quite fully understood)
Here is the code for the class .cpp file
int myVector::at(int i)
{
if(i<vsize)
return array[i];
throw 10;
}
and here is the driver code
#include "myVector.h"
#include <iostream>
using namespace std;
int main()
{
// Create a default vector (cap = 2)
myVector sam;
// push some data into sam
cout << "\nPushing three values into sam";
sam.push_back(21);
sam.push_back(31);
sam.push_back(41);
cout << "\nThe values in sam are: ";
// test for out of bounds condition here
for (int i = 0; i < sam.size( ) + 1; i++)
{
try
{
cout << sam.at(i) << " ";
}
catch(int badIndex)
{
cout << "\nOut of bounds at index " << badIndex << endl;
}
}
cout << "\n--------------\n";
// clear sam and display its size and capacity
sam.clear( );
cout << "\nsam has been cleared.";
cout << "\nSam's size is now " << sam.size( );
cout << "\nSam's capacity is now " << sam.capacity( ) << endl;
cout << "---------------\n";
// Push 12 values into the vector - it should grow
cout << "\nPush 12 values into sam.";
for (int i = 0; i < 12; i++)
sam.push_back(i);
cout << "\nSam's size is now " << sam.size( );
cout << "\nSam's capcacity is now " << sam.capacity( ) << endl;
cout << "---------------\n";
cout << "\nTest to see if contents are correct...";
// display the values in the vector
for (int i = 0; i < sam.size( ); i++)
{
cout << sam.at(i) << " ";
}
cout << "\n--------------\n";
cout << "\n\nTest Complete...";
cout << endl;
system("PAUSE");
return 0;
}
Any help is appreciated. Thanks
The driver that you have provided:
try {
cout << sam.at(i) << " ";
}
catch(int badIndex) {
cout << "\nOut of bounds at index " << badIndex << endl;
}
expects that int will be thrown (a bit weird design, but well... this is the code that will use your class...). Your implementation of at() might look like this:
int& myVector::at(int i) throw(int) {
if (i < vsize)
return array[i];
throw i;
}
just try to follow one simple rule: throw by value, catch by reference.
Also note that you have a pointer:
private:
int* array;
which points to dynamically allocated memory allocated in constructor and copy constructor and freed in destructor :
myVector::myVector(int i)
{
...
array = new int[maxsize];
}
myVector::myVector(const myVector& v)//copy constructor
{
...
array =new int[maxsize];
}
myVector::~myVector()
{
delete[] array;
}
But how about the assignment operator ? See What is The Rule of Three?
Your stop condition of for loop ends it one element after the last one (i.e. you cannot access 4th element of sam vector because there are only three elements).
std::vector::at throws std::out_of_range exception in such situation (see: http://en.cppreference.com/w/cpp/container/vector/at), not int one. So you should change your exception handling part to something like this:
#include <exception>
try
{
cout << sam.at(i) << " ";
}
catch(std::out_of_range exc)
{
cout << "\nOut of bounds at index " << exc.what() << endl;
}