C ++ exception handling by creating a string

My program is as follows: (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 an exception and provide this error message when we put the denominator as 0. The output I get when I enter the denotation, since 0 looks like this:

administrator @ubuntu: ~ / FYMCA / CPP_class $ g ++ prog110.cpp admin @ubuntu: ~ / FYMCA / CPP_class $. / a.out Enter the numerator and denominator: 12 0 termination of the call after calling the instance 'char const *' Aborted (core dumped )

How to solve the problem?

+5
source share
5 answers

String literals are of type char const[]fading to char const*. You must configure the handler accordingly catch:

catch (char const* msg)
//          ^^^^^
{
    cout << msg;
}

.

, , ++:

#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 ";
}

+11

, .

+2

. stdexcept lib, std:: runtime_error std:: logic, std:: exception

+1

(Windows 10) code :: blocks , , , , , msgstr " char const *"

0

A simple fix is ​​to add the instruction to the top as follows:

char * err = "Division by ZERO not possible";

Then change throwtothrow err;

This is due to the way the compiler allocates storage for string literals.

-1
source

All Articles