No output while doing try catch in c++ - c++

I am trying to catch bad allocation error. When input length will be in order of 10000000000000000000000 or something, then bad allocation error should come. I don't know why its not being caught.
Any help will be appreciated!
# include <vector>
# include <iostream>
using namespace std;
void length(int m)
{
vector<int> x;
try
{
x.resize(m);
}
catch(std::bad_alloc&)
{
cout << "caught bad alloc exception" << std::endl;
}
}
int main()
{
int l;
cout << "Length" ;
cin >> l ;
length(l);
return 0;
}
UPDATED:
When I am hard coding the value for input, then it is throwing an exception. I don't know why its working this way.
# include <vector>
# include <iostream>
using namespace std;
void length(int m)
{
vector<int> x;
try
{
x.resize(m);
}
catch(std::bad_alloc&)
{
cout << "caught bad alloc exception" << std::endl;
}
}
int main()
{
int m= 100000000000000000000;
length(m);
return 0;
}

You ought to write
if (!(cin >> l)){
// I could not read that into `l`
}
The lack of an exception being caught could be down to
Your int value being smaller than you think (perhaps some undefined wrap-around behaviour), and an exception is not thrown since the allocation is successful.
The allocation being lazy in the sense that the memory is not allocated until you actually use it.
If std::bad_alloc is thrown as an anonymous temporary then it will not be caught at your catch site. (Unless your naughty compiler allows non-const references to bind to anonymous temporaries, which some do as an extension). Write catch (const std::bad_alloc&) instead, and it will be caught there.

The maximum length of an integer type int is 2.147.483.647 . Are you sure you have actually used an higher number to test it?

You're passing Integer variable which has the limit.
Minimum value for a variable of type short: –32768
Maximum value for a variable of type short: 32767
The error which you will get from your code is std::length_error
To raise the bad allocation error dynamically you can try malloc() with incorrect size OR try below code.
#include <iostream>
#include <new>
int main()
{
try {
while (true) {
new int[100000000ul];
}
} catch (const std::bad_alloc& e) {
std::cout << "Allocation failed: " << e.what() << '\n';
}
}
</i>

No exception is thrown because the int that makes it through to your function void length(int m) is capped at its max value that is much less than vector::max_size(). Consider:
void length(int m)
{
cout << "m is: " << m << " which has a max value: " << numeric_limits<int>::max() << endl;
// ...
}
with the output:
Length10000000000000000000000
m is: 2147483647 and has a max value: 2147483647

Related

Exception handlers on array C++

#include <iostream>
#include <array>
#include <exception>
using namespace std;
template<class T, int N>
void PrintArray(array<T, N> a)
{
for (int i = 0; i < int(a.size()); i++)
{
cout << a[i] << ' '; a[i] = 1 + i;
}
}
int main()
{
array <int, 6> arr = { 1,2,3,4,5,6 };
PrintArray<int, 6>(arr);
cout << "2a pos do arr -> ";
cout << arr[2] << endl;
**cout << arr[7] << endl;**
system("Pause");
return 0;
}
I don't seem to be understanding how to use try catch to handle this exception, or if it is even possible (I believe it is). Can someone please explain how would I handle the non existent element of the array.
Accessing an array out of bounds (whether it is a std::array or a C-style array) using the [] operator is undefined behavior, there is no bounds checking performed, so there is no guarantee of an exception being thrown at all. Best case, an OS exception will be thrown, which you may or may not be able to catch. Worse case, no exception will be thrown at all and you will corrupt memory, which you may or may not notice for a long time if ever.
If you want to guarantee a standardized catchable exception is thrown, use the std::array::at() method, which throws a std::out_of_range exception that you can catch with a standard C++ try/catch block, eg:
#include <iostream>
#include <array>
#include <exception>
#include <cstdlib>
template<class T, int N>
void PrintArray(std::array<T, N> &a)
{
for (size_t i = 0; i < a.size(); ++i)
{
std::cout << a[i] << ' '; a[i] = 1 + i;
}
}
int main()
{
std::array <int, 6> arr = { 1,2,3,4,5,6 };
PrintArray(arr);
std::cout << "2a pos do arr -> ";
std::cout << arr[2] << std::endl;
try {
std::cout << arr.at(7) << std::endl;
}
catch (const std::out_of_range &) {
std::cout << "range error!" << std::endl;
}
std::system("Pause");
return 0;
}
If you try to access an array index which is out of bounds your program will crash - you can't catch that. You just need to guard against it to make sure it cannot happen
EDIT - Of course the replies to this answer are valid, it is not guaranteed to crash. You may even be lucky and get an exception but that's unlikely so no point in trying to handle it.
BUT I stand by the answer - make sure it cannot happen. Theres so many ways to do this, runtime checks, use std::array and at() (with try/catch), ASSERTS the options are endless. It's much better to avoid situations happening through good design than to handle the situation when it has already happened.

C++ exception not handling as expected

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?
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.");
If you want to catch an exception, you should throw an exception, not a const char*.
See this answer: c++ exception : throwing std::string
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.

Exception Handling in underflow while doing POP in Stack

I want to know how to apply exception handling when the top variable reaches to a value -1 (no element left to pop). Currently, I am using cout to nofity the user about the stack underflow and returning 0, which is not a good practice. What improvement overall can be made to this pop function and how to notify user and handle the exception when stack reaches a state of underflow.
int Mystack::pop()
{
if (isEmpty())
{
std::cout << "Stack Underflow" << std::endl;
}
else
{
std::cout << "The popped element is" << A[top];
return A[top--];
}
return 0;
}
The Main Section :
case 4:
std::cout << "POP the element" << std::endl;
s1.pop();
break;
You can throw an out_of_range exception:
#include <stdexcept>
int Mystack::pop()
{
if (isEmpty())
throw std::out_of_range("Stack Underflow");
std::cout << "The popped element is" << A[top];
return A[top--];
}
On the client side:
void foo()
{
Mystack ms;
//...
try
{
ms.pop();
}
catch (const std::out_of_range& oor)
{
std::cerr << "Out of Range error: " << oor.what() << '\n';
}
}
Edit: As the comments below mentioned, you can also derive your own exception from std::exception. Here is a simple example:
#include <stdexcept>
struct myStackException : public std::exception
{
const char *what() const noexcept { return "Stack Overflow"; }
};
int Mystack::pop()
{
if (isEmpty())
throw myStackException();
std::cout << "The popped element is" << A[top];
return A[top--];
}
Live (dummy) example: http://ideone.com/ZyqiQ0
Re
” What improvement overall can be made to this pop function
You can
Make it void to make it more exception safe for other item types.
With the current design, if copying of the popped item fails, then there is no way to recover.
Remove internal output.
assert that the underflow doesn't occur, so that this can be caught in testing.
Thus,
void Mystack::pop()
{
assert( top > 0 );
--top;
}
Wow, what a simplification – and now more exception safe too!
As an alternative to the assert you can throw an exception. That's better than the original, but absolutely not better than the assert. It moves correctness issues into the runtime domain, to be handled and perhaps worked around by each caller site.
The benefit of using C++ exceptions is that error handling code can be separated from user code, alleviating the need for code to be littered with error handling code that is common in C programs. Throwing an exception also offers a solution to returning a invalid value in the error case
if( s1.pop() == 0 ){
// is this an error or not?
}
Exceptions can be added to your code like so, by taking advantage in the generic exceptions in the
#include <stdexcept>
header file.
int Mystack::pop()
{
if (isEmpty())
{
throw std::range_error("nothing to pop");
}
std::cout << "The popped element is" << A[top];
return A[top--];
}
Then you add a try/catch block to the appropriate code, perhaps with
case 4:
std::cout << "POP the element" << std::endl;
try{
s1.pop();
}
catch(const std::range_error& e)
{
std::cerr << "unable to pop!\n";
// error handling code
}
break;
Another solution, particularly appropriate when errors aren't as exceptional, such as with file I/O is more intrusive to the user code, but offers a better solution than returning an arbitrary value
int Mystack::pop(int& value)
{
if( isEmpty() )
{
return 1;
}
std::cout << "The popped element is" << A[top];
value = A[top--];
return 0
}
And then your code becomes
case 4:
std::cout << "POP the element" << std::endl;
{
int value;
if( s1.pop(value) == 1 ){
// error code
}
}
break;

How to check a function pointer exists

In C++, I'm trying to write a function with function pointers. I want to be able to throw an exception if a function pointer is passed for a function that does not exist. I tried to handle the function pointer like a normal pointer and check if it is null
#include <cstddef>
#include <iostream>
using namespace std;
int add_1(const int& x) {
return x + 1;
}
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (funcPtr != NULL) {
return funcPtr(x);
} else {
throw "not a valid function pointer";
}
}
int main(int argc, char** argv) {
try {
int x = 5;
cout << "add_1 result is " << add_1(x) << endl;
cout << "foo add_1 result is " << foo(x, add_1) << endl;
cout << "foo add_2 result is " << foo(x, add_2) << endl; //should produce an error
}
catch (const char* strException) {
cerr << "Error: " << strException << endl;
}
catch (...) {
cerr << "We caught an exception of an undetermined type" << endl;
}
return 0;
}
but that doesn't seem to work. What is the best way to do this?
Checking for NULL is ok. But it is not possible to pass a pointer to a function that does not exist in the first place. So you don't have to worry about this. Although it is possible to just declare a function without defining it and pass the address of it. In that case you will get linker error.
It will automatically throw an error if you are passing pointer which does not exist, if you are declaring a pointer then you have to initialize it with null to avoid garbage value, so comparing with null will not serve any purpose.
you still you want to check then try to assign some function(like add, sub etc.), if it takes then ok , if not then it will show again error as previously mentioned.
#include<cstddef>
#include <iostream>
using namespace std;
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (*funcPtr != NULL) {
return funcPtr(x);
}
else
{
cout << "not a valid function pointer";
}
}
If you want to 'throw' exception then you need to 'catch' it as well.
Your code is failing because of two reasons in short,
1) You are not checking value of function pointer.
2) You are not properly catching the thrown exception.

How to create exceptions?

So I have an upcoming assignment dealing with exceptions and using them in my current address book program that most of the homework is centered around. I decided to play around with exceptions and the whole try catch thing, and using a class design, which is what I will eventually have to do for my assignment in a couple of weeks. I have working code that check the exception just fine, but what I want to know, is if there is a way to standardize my error message function, (i.e my what() call):
Here s my code:
#include <iostream>
#include <exception>
using namespace std;
class testException: public exception
{
public:
virtual const char* what() const throw() // my call to the std exception class function (doesn't nessasarily have to be virtual).
{
return "You can't divide by zero! Error code number 0, restarting the calculator..."; // my error message
}
void noZero();
}myex; //<-this is just a lazy way to create an object
int main()
{
void noZero();
int a, b;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
myex.noZero(b); // trys my exception from my class to see if there is an issue
}
catch(testException &te) // if the error is true, then this calls up the eror message and restarts the progrm from the start.
{
cout << te.what() << endl;
return main();
}
cout <<endl;
cout << "The two numbers divided are " << (a / b) << endl; // if no errors are found, then the calculation is performed and the program exits.
return 0;
}
void testException::noZero(int &b) //my function that tests what I want to check
{
if(b == 0 ) throw myex; // only need to see if the problem exists, if it does, I throw my exception object, if it doesn't I just move onto the regular code.
}
What I would like to be able to do is make it so my what() function can return a value dependent on what type of error is being called on. So for instance, if I were calling up an error that looked a the top number,(a), to see if it was a zero, and if it was, it would then set the message to say that "you can't have a numerator of zero", but still be inside the what() function. Here's an example:
virtual const char* what() const throw()
if(myex == 1)
{
return "You can't have a 0 for the numerator! Error code # 1 "
}
else
return "You can't divide by zero! Error code number 0, restarting the calculator..."; // my error message
}
This obviously wouldn't work, but is there a way to make it so I'm not writing a different function for each error message?
Your code contains a lot of misconceptions. The short answer is yes, you can change what() in order to return whatever you want. But let's go step by step.
#include <iostream>
#include <exception>
#include <stdexcept>
#include <sstream>
using namespace std;
class DivideByZeroException: public runtime_error {
public:
DivideByZeroException(int x, int y)
: runtime_error( "division by zero" ), numerator( x ), denominator( y )
{}
virtual const char* what() const throw()
{
cnvt.str( "" );
cnvt << runtime_error::what() << ": " << getNumerator()
<< " / " << getDenominator();
return cnvt.str().c_str();
}
int getNumerator() const
{ return numerator; }
int getDenominator() const
{ return denominator; }
template<typename T>
static T divide(const T& n1, const T& n2)
{
if ( n2 == T( 0 ) ) {
throw DivideByZeroException( n1, n2 );
}
return ( n1 / n2 );
}
private:
int numerator;
int denominator;
static ostringstream cnvt;
};
ostringstream DivideByZeroException::cnvt;
In the first place, runtime_error, derived from exception, is the adviced exception class to derive from. This is declared in the stdexcept header. You only have to initialize its constructor with the message you are going to return in the what() method.
Secondly, you should appropriately name your classes. I understand this is just a test, but a descriptive name will always help to read and understand your code.
As you can see, I've changed the constructor in order to accept the numbers to divide that provoked the exception. You did the test in the exception... well, I've respected this, but as a static function which can be invoked from the outside.
And finally, the what() method. Since we are dividing two numbers, it would be nice to show that two numbers that provoked the exception. The only way to achieve that is the use of ostringstream. Here we make it static so there is no problem of returning a pointer to a stack object (i.e., having cnvt a local variable would introduce undefined behaviour).
The rest of the program is more or less as you listed it in your question:
int main()
{
int a, b, result;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
result = DivideByZeroException::divide( a, b );
cout << "\nThe two numbers divided are " << result << endl;
}
catch(const DivideByZeroException &e)
{
cout << e.what() << endl;
}
return 0;
}
As you can see, I've removed your return main() instruction. It does not make sense, since you cannot call main() recursively. Also, the objective of that is a mistake: you'd expect to retry the operation that provoked the exception, but this is not possible, since exceptions are not reentrant. You can, however, change the source code a little bit, to achieve the same effect:
int main()
{
int a, b, result;
bool error;
do {
error = false;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
result = DivideByZeroException::divide( a, b ); // trys my exception from my class to see if there is an issue
cout << "\nThe two numbers divided are " << result << endl;
}
catch(const DivideByZeroException &e) // if the error is true, then this calls up the eror message and restarts the progrm from the start.
{
cout << e.what() << endl;
error = true;
}
} while( error );
return 0;
}
As you can see, in case of an error the execution follows until a "proper" division is entered.
Hope this helps.
You can create your own exception class for length error like this
class MyException : public std::length_error{
public:
MyException(const int &n):std::length_error(to_string(n)){}
};
class zeroNumerator: public std::exception
{
const char* what() const throw() { return "Numerator can't be 0.\n"; }
};
//...
try
{
myex.noZero(b); // trys my exception from my class to see if there is an issue
if(myex==1)
{
throw zeroNumerator(); // This would be a class that you create saying that you can't have 0 on the numerator
}
}
catch(testException &te)
{
cout << te.what() << endl;
return main();
}
You should always use std::exception&e. so do
catch(std::exception & e)
{
cout<<e.what();
}
You should consider a hierarchy of classes.
The reason for it might not be obvious when trying to use exceptions just for transferring a string, but actual intent of using exceptions should be a mechanism for advanced handling of exceptional situations. A lot of things are being done under the hood of C++ runtime environment while call stack is unwound when traveling from 'throw' to corresponded 'catch'.
An example of the classes could be:
class CalculationError : public std::runtime_error {
public:
CalculationError(const char * message)
:runtime_error(message)
{
}
};
class ZeroDeviderError : public CalculationError {
public:
ZeroDeviderError(int numerator, const char * message)
: CalculationError(message)
, numerator (numerator)
{
}
int GetNumerator() const { return numerator; }
private:
const int numerator;
};
Providing different classes for the errors, you give developers a chance to handle different errors in particular ways (not just display an error message)
Providing a base class for the types of error, allows developers to be more flexible - be as specific as they need.
In some cases, they might want to be specific
} catch (const ZeroDividerError & ex) {
// ...
}
in others, not
} catch (const CalculationError & ex) {
// ...
}
Some additional details:
You should not create objects of your exceptions before throwing in the manner you did. Regardless your intention, it is just useless - anyway, you are working with a copy of the object in the catch section (don't be confused by access via reference - another instance of the exception object is created when throwing)
Using a const reference would be a good style catch (const testException &te) unless you really need a non-constant object.
Also, please note that the type (classes) used for exceptions are not permitted to throw exceptions out of their copy constructors since, if the initial exception is attempted to be caught by value, a call of copy constructor is possible (in case is not elided by the compiler) and this additional exception will interrupt the initial exception handling before the initial exception is caught, which causes calling std::terminate.
Since C++11 compilers are permitted to eliminate the copying in some cases when catching, but both the elision is not always sensible and, if sensible, it is only permission but not obligation (see https://en.cppreference.com/w/cpp/language/copy_elision for details; before C++11 the standards of the language didn’t regulate the matter).
Also, you should avoid exceptions (will call them the additional) to be thrown out of constructors and move constructors of your types (classes) used for exceptions (will call them initial) since the constructors and move constructors could be called when throwing objects of the types as initial exceptions, then throwing out an additional exception would prevent creation of an initial exception object, and the initial would just be lost. As well as an additional exception from a copy constructor, when throwing an initial one, would cause the same.