When to catch an exception?

I know how exception handling works, but how should I actually use it in action? Let's say I have something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Class X
{
public:
X();
//Pre-condition: example can't be 3.
void number(int example);
};

void X::number(int example)
{
//exception handing here
}

{
...
X* badNumber = new X();
int badExample = 3;
badNumber->number(badExample);
...
}


So what is the optimal way of handling the exception? For instance, would this be bad practice?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void X::number(int example)
{
try
{
   if (example == 3)
   {
      throw example;
   }
   catch(int badNumber)
   {
      cout << badNumber << " is a bad number";
      //Program is shut down
   }
}
...
//the rest of the code
...
}


If I know that the exception can only happen at the beginning of the function, is it okay to catch it right away? Are there any problems with that?
Last edited on
The exception doesn't have to be thrown only at the beginning.
It can be thrown from any point of any function.
In my opinion you should let the enduser handle the exception.
Eg. The class function throws, and the caller of the function catches.
1
2
3
4
void X::number(int n){if(n== 3) throw n; //...
X x;
try{x.number(3);}
catch(int n){std::cout << n << std::endl;}
If you have something like
1
2
3
4
5
try {
    throw foo;
} catch(foo&){
    /*...*/
}
It smells. Exceptions should be thrown when you cannot handle error in current context and want to delegate responsibility to caller function.
Likewise you should catch exception when you have something to do with it: you can handle it here, you want to repackage exception, you want to log exception occurence...

BTW, in your case program will not be shut down because you handled exception.
Also you made a mistake in try...catch blocks: catch should follow try, as else follows if.

In your case you can do something like:
1
2
3
4
5
6
7
void X::number(int example)
{
    if (example == 3) 
        //Letting caller decide what to do with exception as we do not know.
        throw std::domain_error("3 is not valid number");
    //...
}
+1 to MiiNiPaa.

Also, don't use new, and if you do, don't put the result in a C-style pointer if you have any chance of encountering exceptions.
"C-style pointer" wait there is another kind of pointers??
smart pointers:
1
2
3
std::unique_ptr<X> badNumeber = new X();
//or in C++14
auto badNumber = make_unique<X>();
badNumber will be automatically deleted when it goes out of scope, or when exception is thrown, what C-style pointers cannot promise. Also it denotes ownership on object.
Hi,

1 more thing, one can try & catch exceptions in initialiser lists in a constructor:

http://www.cprogramming.com/tutorial/initialization-lists-c++.html


Hope this is useful, it's a bit off topic.

Cheers
Now THAT is something I didn't know.
Topic archived. No new replies allowed.