Stroustrup PPP: 5.5.1 The caller deals with errors

Sorry for the repeat post! I posted here first. Then I found the General C++ Programming section, and thought that would be a better place for the post. PLEASE DELETE THIS THREAD!
Last edited on
Compiles fine and throws exception as expected using GCC 6.2

Dump that #include "stdafx.h" at the front; you don't need it.

I see that error takes a string, and you're passing it a char-pointer. What happens if you explicitly make the string?

1
2
std::string temp("non-positive x");
if (x <= 0) error(temp);
Last edited on
Hi Repeater,

Thanks for trying to help! I used your suggestions to try to make the program work, but was unsuccessful!

First, I think I need that header file. Without it, the first program I wrote ("Hello World") did not work...

Second, creating the error message as a string and then using it as an argument in the error() function did not work.
AfineyoungSc0ut,

It shouldn't make a difference if you pass a string literal or a string object - the string literal will be implicitly converted to a string.

There's an important step you're missing - though it won't help you with your compilation error: You're not catching / handling the thrown exception!

If you take a look at how 'error' is implemented, it's just wrapper for throwing a runtime error. You'll have to handle the exception in a try-catch block.

I don't know why you're getting a compilation error. The following code works for me:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include "std_lib_facilities.h"

int main() {

	try {
		error("test");
	}
	catch (const std::runtime_error& error) {
		std::cout << error.what() << std::endl;
	}

	return 0;
}
Last edited on
closed account (E0p9LyTq)
Please don't create multiple posts:
http://www.cplusplus.com/forum/general/200394/
Topic archived. No new replies allowed.