Exception handeling

I want to demonstrate all exception in one program. I try to demonstrate in a single program. But i am confused is my code right for this question?(Write a C++ program to demonstrate catching all exceptions.)
can anyone please answer it it ok or not?
Here I attach my code


#include <iostream>
using namespace std;
int main()
{
int a=10, b=0, c;

try
{
if(b == 0)
{
throw ('I');
c = a/b;
}
}
catch(char I)
{
cout<<"Division by zero not possible"<<endl;
}
return 0;
}
Last edited on
When they say "catching all exceptions" they probably mean you should use catch (...) to catch all exceptions no matter what type that is thrown.

You probably want to do the division outside the if statement. Right now the division never takes place and the result is never used for anything.
Hello drhunter,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.


Along with Peter87's suggestion I did get this to work with MSVS 2017:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

using namespace std;

int main()
{
    int a = 10, b = 0, c;

    try
    {
        if (b == 0)
        {
            throw 1;  // <--- It does not matter what you throw.
        }
        
        c = a / b;
    }
    catch(...)
    {
        cout << "\n     Division by zero not possible." << endl;
    }

    return 0;  // <--- Not required, but makes a good break point.
}


You might want to have a look at https://en.cppreference.com/w/cpp/language/try_catch

Andy
Thank you Andy
Topic archived. No new replies allowed.