Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

try & catch structure in C#

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.

like image 458
WisperWordsOfwisdom_code_in_c_ Avatar asked Sep 08 '26 02:09

WisperWordsOfwisdom_code_in_c_


2 Answers

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.

like image 94
CodesInChaos Avatar answered Sep 10 '26 16:09

CodesInChaos


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;
}
like image 30
coder_bro Avatar answered Sep 10 '26 14:09

coder_bro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!