If I have a method that returns something, like
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
}
This produces compiler error, obviously because catch{}
block does not return anything.
So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?
It depends on you application. You can return
null
, an emptyDataTable
or whatever is suitable under circumstances.You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.
Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.
For my example, this would be coded as follows...
Store your return value in a temporary variable like this:
Since you are cacthing the exception (and not throwing it again) in your example, The outside code assumes everyting is okay and therefor you should return something useful.
If you need to catch the exception there and do somthing that's all fine, but if it's still an error case you should also throw it, or a different exception, perhaps with the one you just caught as InnerException.
i'd assume you can still set the message, then return null or whatever the c# equivalent is
You should raise/throw the exception in your catch block and handle it in the calling method.
PS: Sorry for any syntax error, I'm a bit rusty on C#.