Exception handling in C++

Hey so I was just curious if exception handling was done in the same way as java. For example, I want to take user input that is only numeric, because it is being stored in an int. Could I just do

1
2
3
4
5
try
 cin >> userNumber;
catch
 cout << "Error message";
end try
IO streams report errors by setting flags by default, you have to enable exceptions explicitly, like so:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
int main()
{
    std::cin.exceptions(std::ios::failbit);
    try {
        int userNumber;
        std::cin >> userNumber;
    } catch(const std::ios_base::failure& e) {
        std::cout << "Error message\n";
    }
}

demo: http://ideone.com/sNHPm

Most people check the status of cin instead of using I/O exceptions, though, since input errors are, in most cases, expected.
You could also check manually if the stream fails.

1
2
3
4
5
6
7
8
int i;

cin >> i;

if (cin.fail())
	cout << "FAIL!\n";

Last edited on
so cin will fail if they try enter a string when it's expecting a numeric value? What if they enter a decimal value? Will c++ just do some implicit type casting?
A string will read anything but I believe an int will truncate a decimal. These are things that you should just google and find out for yourself.

But entering a char into a numeric data type will cause the stream to fail. Exception handling in C++ is not that great compared to Java, VB, C#, etc so it's better to just use logic to handle the simple errors instead.

I always return bools when creating functions that read or validate data so that I can just simply put them in while loops until data is valid. No need for exception handling.



Topic archived. No new replies allowed.