I'm new to programming and was wanting to ask, is the code shown below a good way to use the try catch within a boolean method?
It's just example code but I have many methods within my Presenter classes and was wondering the way I placed the catch just returning false, is this ok to do, or how else could I improve this
public bool TestMethod()
{
try
{
if(true)
{
//some random code
return true;
}
else{return false;}
}
catch{return false;}
}
I just wanted to be sure it a good way to implement this, I would appreciate any feedback on how this could improved.
Don't use a catch-all in such a way. Catching all exceptions is acceptable for the top level exception handler. But it shouldn't just swallow them. But log them and perhaps display an error.
For your code you should only catch the specific exception types you're expecting. And I'm not sure if in your example exceptions are a good idea at all.
Here are some points, which I find a bit discerning about the code in the question:
There are multiple return statements in the code at various places, this may be confusing to the reader of the code. We generally tend to follow a single return statement in a function. (All though there are some exceptions to rule, like an early return in case of some error condition)
Generally you should never hide an exception from the user (or some say "never swallow an exception"), you should either rethrow it or handle the exception and display it to the user.
In the least, there should be some log of the exception.
So with these points in mind, the above code can be written as:
public bool TestMethod()
{
bool returnValue = false;
try
{
if(true)
{
//some random code
returnValue = true;
}
}
catch(Exception ex)
{
// log the exception here, or rethrow it
}
return returnValue;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With