Exceptions and what()

When I run the below code, the runErr.what() does not print anything. I have no clue why. Also, sometimes what() function prints things different from what my book says you should see, and why is that?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;

string findItem(string *array, int size, string target) throw(logic_error)
{
    int index = 0;
    bool found = false ;

    while (!found && (index < size))
    {
        if (target == array[index])
            found = true ;

        else
            index++;
    }

    if (!found)
        throw logic_error("Target not found in a array!");

    return array[index];
}

int main(){

    string stuff[4] = {"Keys", "Food", "Glasses", "Cheese"};

    string a_thing;

    try 
    {
	a_thing = findItem(stuff, 5, "Pants");

    }


    catch(runtime_error runErr)
    {

        //This cout statement prints nothing!
        cout << runErr.what() << endl;

        a_thing = "Nothing";
    }

    return 0;
}
Last edited on
When I run the below code, the runErr.what() does not print anything. I have no clue why
Because you never caught thrown exception. You are throwing logic_error but capturing runtime_error. runtime_error is not a base class of logic_error.

Also:
1) Throw specificalions are deprecated. Do not use them, they make more trouble that it worth.
2) throw by value capture by reference.

Your line 40 should look:
1
2
3
catch(logic_error& runErr)
//Or
catch(exception& runErr)



Also, sometimes what() function prints things different from what my book says you should see, and why is that?
Can you give an example?
Last edited on
I have updated to the below code, but what() still prints nothing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;


string findItem(string *array, int size, string target) throw(runtime_error)
{
	int index = 0;
	bool found = false ;

	while (!found && (index < size))
	{
		if (target == array[index])
			found = true ;

		else
			index++;
	}


	if (!found)
		throw runtime_error("Target not found in a array!");

	return array[index];
}



int main(){

    string stuff[4] = {"Keys", "Food", "Glasses", "Cheese"};

    string a_thing;

    try 
    {
	a_thing = findItem(stuff, 5, "Pants");

    }

//The catch below runs, so it's a runtime_error. But runErr.what() prints nothing.
	catch(runtime_error& runErr)
	{
		cout << runErr.what() << endl;
		cout << "runtime_error" << endl;

		a_thing = "Nothing";


	}

    return 0;
}



An example of two different prints what() after execution is for the code below:

The book says you should see :

The string does not contain 99 characters.
invalid string position

My IDE, Cygwin, prints:

The string does not contain 99 characters.
basic_string::replace



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

// Encodes the character at index i of the string str.
void encodeChar( int i, string& str)
{
	int base = static_cast < int >('a');
	
	//isupper checks if the character is upper case.
	if (isupper(str[i]))
		base = int ('A');

	char newChar = ( static_cast < int>(str[i]) - base + 3) % 26 + base;
	str.replace(i, 1, 1, newChar); // Method replace can throw exception
} // end encodeChar


// Encodes numChar characters within a string.
void encodeString( int numChar, string& str)
{
	try
	{
		for ( int i = numChar - 1; i >= 0; i--)
			encodeChar(i, str);
	}
	catch (out_of_range e)
	{
		cout << "The string does not contain " << numChar;
		cout << " characters." << endl;
		cout << e.what() << endl;
	} // end try-catch
} // end encodeString

int main(){


	string str1 = "Sarah";
	encodeString(99, str1);
	return 0;
} // end main 
Last edited on
You have a problem.
1
2
string stuff[4] = {"Keys", "Food", "Glasses", "Cheese"};
a_thing = findItem(stuff, 5, "Pants");
There is a great chance that your program will crash before exception will be thrown.

Also, remove throw specifier from your function:
string findItem(string *array, int size, string target) throw(runtime_error)


An example of two different prints what() after execution is for the code below
Text of exception text generated by standard library is implementation defined. So different compilers would have different text.

You have a problem.

1
2
string stuff[4] = {"Keys", "Food", "Glasses", "Cheese"};
a_thing = findItem(stuff, 5, "Pants");


There is a great chance that your program will crash before exception will be thrown.



Why is that? Is it because the loop is going two places above the maximum index of the array? So it might crash before it reaches the last one?

Also, why do we not need throw(runtime_error)? Isn't the code only throwing a runtime_error?

I changed the code, but it still doesn't print what():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <stdexcept>
#include <string>
using namespace std;


string findItem(string *array, int size, string target) 
{
	int index = 0;
	bool found = false ;

	while (!found && (index < size))
	{
		if (target == array[index])
			found = true ;

		else
			index++;
	}


	if (!found)
		throw runtime_error("Target not found in a array!");

	return array[index];
}


int main(){

	string stuff[5] = {"Keys", "Food", "Glasses", "Cheese", "Skeleton"};

	string a_thing;

	try 
	{
		a_thing = findItem(stuff, 5, "Pants");

	}

	catch(runtime_error& runErr)
	{
                //runErr.what() still prints nothing.
		cout << runErr.what() << endl;
		cout << "runtime_error" << endl;

		a_thing = "Nothing";


	}

	cout << a_thing << endl;

	return 0;

}

Last edited on
Everything is fine, check if you are building latest version of your code:
http://ideone.com/DZ1jUI
http://coliru.stacked-crooked.com/a/3278f0bccac5896a
http://melpon.org/wandbox/permlink/ZETWhBcngJ5dWg8T


Also, why do we not need throw(runtime_error)? Isn't the code only throwing a runtime_error?
It is deprecated. It made more problems than it solves.
And actually your code can throw bad_alloc too, not only runtime_error
Everything is fine, check if you are building latest version of your code:
http://ideone.com/DZ1jUI
http://coliru.stacked-crooked.com/a/3278f0bccac5896a
http://melpon.org/wandbox/permlink/ZETWhBcngJ5dWg8T


Cygwin prints out the same exact thing printed out in the above three links. My professor skipped exceptions, so I am trying to learn it on my own. So might I be missing something that's not making runErr.what() print something?
Last edited on
If you are using an IDE, make sure you are running the correct code
If you are using an IDE, make sure you are running the correct code


You mean like when I first installed my IDE, I also have to select codes for exception's what() function to be installed?
Last edited on
Topic archived. No new replies allowed.