exceptions

Write a C + + program that asks the user a value for the width; and then displays the corresponding square area. If the width is not an integer, the situation will be treated as an exception. Exception handling subroutine will restore the width to 0 and will warn the user of the mistake made.
if anybody can help me tyo solve this with or without classes.
thank you
Last edited on
Do you know how to throw and catch exceptions?

You throw and catch them by their type. Because each exception needs to have a different type, the C++ library offers an std::exception class that you can derive your own exceptions from, to make your job easier.

http://www.cplusplus.com/reference/exception/exception/exception/

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
#include <exception>
#include <iostream>

class ExampleException: public std::exception
{
public:

    const char * what() const throw()
    {
        return "your error message goes here";
    }
};

void ex_function()
{
    throw ExampleException();
}

int main()
{
    try
    {
        ex_function();
    }
    catch (const ExampleException &ee)
    {
        std::clog << "Exception caught: " << ee.what() << ".\n";
    }
}


Exception caught: your error message goes here.

1
2
3
4
5
6
int width;
for (std::cout << "Enter a value: "; !(std::cin >> width); std::cout << "Enter a value: ")
{
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cin.clear();
}
Last edited on
Topic archived. No new replies allowed.