Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling in C++ by throwing a string

Tags:

c++

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?

like image 801
Tejashree Vaze Avatar asked Apr 03 '13 17:04

Tejashree Vaze


2 Answers

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.

like image 188
Andy Prowl Avatar answered Sep 29 '22 03:09

Andy Prowl


The exception message kind of says it, you're catching the wrong type.

like image 27
Some programmer dude Avatar answered Sep 29 '22 02:09

Some programmer dude