runtime_error clarification

Hi all, I'm using the book "Principles and Practice Using C++" by Bjarne Stroustrup to learn C++ at the moment. I'm now on chapter 5, errors.

In this chapter, they provided examples about how to deal with errors.
For example,

1
2
3
4
5
6
7
//calculate area
int x, y;
cin>>x>>y;

//if x or y is negative, give error
if (x<0 || y<0) error("non positive inputs");
else int area=x*y;


The issue comes next. When a negative value is entered, I expected a message would pop out, telling me that an error has occurred with the message "non positive inputs" appearing on it. However, I got this error message instead.

"An unhandled exception of type 'System.Runtime.InteropServices.SEHException' occurred in learning_from_book.exe

Additional information: External component has thrown an exception."

When I clicked on break, it opens the header "std_lib_facilities.h" that the book asked us to reference, and points to this segment of the code.

1
2
3
4
5
// error() simply disguises throws:
inline void error(const string& s)
{
	throw runtime_error(s);
}


So my question is, is the error() doing what it is supposed to do? Because my message didn't appear, I am assuming that it's not working.


EDIT: I forgot to mention I'm using Visual C++ Express 2010.
Last edited on
is the error() doing what it is supposed to do?

Yes and no.

It looks as though your code should have a try-catch block.

You would usually get an "unhandled exception" message when either the catch block is missing, or it wasn't set up to catch that particular type of error.
http://www.cplusplus.com/doc/tutorial/exceptions/
Last edited on
Also, unfortunately he has also created a C++/CLI microsoft project and not a C++ project - he should really correct that as well.
Ok, I think I'm getting it now.

So basically, just throwing a runtime_error will just result in the default pop-up "An unhandled exception of type ...". In order to display custom error messages, we need to include a try-catch block.

Since error() throws a runtime_error, I need to catch the runtime_error like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
try {
	//calculate area
	int x, y;
	cin>>x>>y;

	//if x or y is negative, give error
	if (x<0 || y<0) error("non positive inputs");
	else int area=x*y;

} catch (runtime_error& e) {
	cerr<<"runtime error: "<<e.what()<<"\n";
	keep_window_open();
	return 1;
}


Can you confirm if I got the basic idea down?

@guestgulkam:
I'm not sure what you mean by that. Do you mean the book examples were created in a C++/CLI microsoft project? What's the difference?
Can you confirm if I got the basic idea down?
That looks reasonable. If it behaves correctly when you run it, that would be a useful indication
Yup, it does. I've tested it. Thanks a lot!
Topic archived. No new replies allowed.