In general I want to make a code that makes a call an Execute function of a class which may throw an exception. My question is should I setup the class and should I extract the values from it within the try/catch or out side?
Option A:
neededValue V;
try
{
MyClass C = new MyClass();
C.SomeParam = XXX;
C.Execute();
V = C.SomeParam2;
}
catch
{
//Clean up...
//Log...
//Throw new exception
}
Option B:
neededValue V;
MyClass C = new MyClass();
C.SomeParam = XXX;
try
{
C.Execute();
}
catch
{
//Clean up...
//Log...
//Throw new exception
}
V = C.SomeParam2;
I know both will work, but which is nicer and easiest to read?
I would say option B is easier to read and more practical because you will know later that the Execute can throw and Exception.
They are not the same, in option B if you handle the exception then your B variable will be set too and not only if your Execute succeeds.
And you should always specify with the catch block what kind of exception you are catching and so you can handle it and/or Log it correctly.