What is better coding practice: if I have to have a try/catch block shall I place everything (every initialization and so on) in this block or just those variables which may throw? Is there any difference between those two constructions?
In example:
Having:
struct A {
A();
int a;
int* b;
};
and later on in .cpp:
A::A() {
a = 5;
try {
b = new int;
}
catch(...){
}
}
or
A:A() {
try {
a = 5; //this time in try block
b = new int;
}
catch(...) {
}
}
is there any difference between those two constructs or is this in a way if I have to have a try/catch block I may aswell put everything in it?
Thank you.
P.S.
For God efin sake, formatting here drives me really crazy! And I know that I mentioned this many times, I’m not going mad.
I think a good general principle is to make a
tryblock as “narrow” as possible — don’t put in it things that you believe won’t ever cause exceptions. That way, should you ever be wrong and have one of those “can’t cause exception” parts actually do cause an exception, you won’t be accidentally “swallowing” the astonishing exception (and no doubt dealing with it in inappropriate ways, since your code would not be expecting that exception but other kinds).