Reputation: 51
My program is following : (on linux)
// Ex. 2 of Exception Handling
// Here divn() raises the exception but main() will be the exception handler
#include<iostream>
using namespace std;
int divn(int n, int d)
{
if(d == 0)
throw "Division by ZERO not possible ";
return n/d;
}
main()
{
int numer, denom;
cout << "Enter the numerator and denominator : ";
cin >> numer >> denom;
try
{
cout << numer << " / " << denom << " = " << divn(numer,denom) << endl;
}
catch(char *msg)
{
cout << msg;
}
cout << "\nEnd of main() \n ";
}
/*it should throw the exception and provide the given error message when we put denominator as 0. the output I get when i enter the denom as 0 is as follows :
administrator@ubuntu:~/FYMCA/CPP_class$ g++ prog110.cpp administrator@ubuntu:~/FYMCA/CPP_class$ ./a.out Enter the numerator and denominator : 12 0 terminate called after throwing an instance of 'char const*' Aborted (core dumped)
How do I solve the problem?
Upvotes: 5
Views: 12626
Reputation: 126552
String literals have type char const[]
, decaying to char const*
. You should adjust your catch
handler accordingly:
catch (char const* msg)
// ^^^^^
{
cout << msg;
}
Here is a live example.
Finally, here is a better way to rewrite your program, using exception classes from the C++ Standard Library:
#include <iostream>
#include <stdexcept>
// ^^^^^^^^^^^ For std::logic_error
int divn(int n, int d)
{
if(d == 0)
{
throw std::logic_error("Division by ZERO not possible ");
// ^^^^^^^^^^^^^^^^
// Throw by value
}
return n/d;
}
int main() // <== You should specify the return type of main()!
{
// Rather use these than "using namespace std;"
using std::cout;
using std::cin;
using std::endl;
int numer, denom;
cout << "Enter the numerator and denominator : ";
cin >> numer >> denom;
try
{
cout << numer << " / " << denom << " = " << divn(numer,denom) << endl;
}
catch(std::logic_error const& err)
// ^^^^^^^^^^^^^^^^^^^^^^^
// Catch by reference
{
cout << err.what();
// ^^^^^^^^^^
}
cout << "\nEnd of main() \n ";
}
And the corresponding live example of course.
Upvotes: 11
Reputation: 8839
A simple fix is to add a statement towards the top as follows:
char * err = "Division by ZERO not possible";
Then, change your throw
to throw err;
It has to do with how the compiler allocates storage for string literals.
Upvotes: -1
Reputation: 409442
The exception message kind of says it, you're catching the wrong type.
Upvotes: 2
Reputation: 7929
You should not throw exceptions in such a manner. A good practice is using standard exceptions in stdexcept lib such as std::runtime_error or std::logic error or creating your own exception class based on the std::exception
Upvotes: 1