简体   繁体   English

C#中的try & catch结构

[英]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?我是编程新手,想问一下,下面显示的代码是在布尔方法中使用 try catch 的好方法吗?

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这只是示例代码,但我的 Presenter 类中有很多方法,并且想知道我放置捕获的方式只是返回 false,这样做可以吗,或者我还能如何改进它

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.代码中的不同地方有多个 return 语句,这可能会使代码的读者感到困惑。 We generally tend to follow a single return statement in a function.我们通常倾向于在函数中遵循单个 return 语句。 (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;
}

IMHO its not the purpose of the catch-block to return values.恕我直言,它不是 catch 块返回值的目的。 I'll use it this way:我会这样使用它:


public bool TestMethod()
{
    bool retVal = false;
    try
    {
        if (true)
        {
            //some random code
            retVal = true;
        }
        else{}
    }
    catch{}
    return retVal;
}

It depends on what you do in your if block.这取决于您在 if 块中执行的操作。 If you return false on an unexpected error, you'll never be able to know what went wrong.如果您对意外错误返回 false,您将永远无法知道出了什么问题。 If your code is simple enough and you know for what went wrong, it is a good usage.如果您的代码足够简单并且您知道出了什么问题,那么这是一个很好的用法。

For example, it is a good approach for a method which checks if the given string is a valid number and multiplier of 5. If it is not a number, you'll get an exception and you don't need to log it or nothing else can cause an exception.例如,对于检查给定字符串是否为有效数字和 5 的乘数的方法来说,这是一个很好的方法。如果它不是数字,您将得到一个异常并且您不需要记录它或什么都不记录否则可能导致异常。

The point here is readability and everybody has his style (this is not a matter of right and wrong).这里的重点是可读性,每个人都有他的风格(这不是对与错的问题)。 What I do is declaring a return value (as some guys did here like retVal , returnValue ,...), my favorite is result which in your case should be a bool .我所做的是声明一个返回值(就像这里的一些人所做的一样retValreturnValue ,...),我最喜欢的是result在你的情况下应该是一个bool

Then playing with this result variable in method body ie inside try/catch and DO NOT return anything unless at the end of method where I return result .然后在方法体中使用这个result变量,即在try/catch ,除非在我返回result的方法结束时,否则不要返回任何内容。 Personally use return where the remaining code (after return ) should not be run.个人在不应运行剩余代码(在return之后)的地方使用return

This way the reader would not confused of so many return s.这样读者就不会被这么多的return弄糊涂了。 You may think about performance benefits of early returns which I doubt (if compiler optimization cannot do it for you) it has a little effect in the world of frameworks and layers , where we are sacrificing performance for design issues in a daily basis.您可能会考虑早期returns性能优势,我对此表示怀疑(如果编译器优化无法为您完成)它在frameworkslayers的世界中影响不大,我们每天都在为设计问题牺牲性能。

Finally, take the point CodeInChaos said seriously.最后,认真对待CodeInChaos所说的这一点。 If you don't know an exception reason and would not take care of it in a graceful fashion, leave it to be thrown.如果您不知道异常原因并且不会以优雅的方式处理它,请将其抛之脑后。 Exceptions are not bad things, they are like pain in medicine. Exceptions并不是坏事,它们就像医学上的痛苦。 A chronic diabetic person who has lost the pain in his feet, will not notice small injuries in his feet and a google search will should you the pictures resulting of ignoring painful signals.一个失去脚痛的慢性糖尿病患者不会注意到脚上的小伤, 谷歌搜索会发现因忽略疼痛信号而产生的图片。

It is certainly OK to return directly from inside a catch clause, if that's what you're asking.如果这就是您要问的,那么直接从catch子句内部返回当然是可以的。 Otherwise the compiler would prohibit it;否则编译器会禁止它; for example, you can't return from inside a finally clause.例如,您不能从finally子句中返回。

In your particular code example, however, the catch clause seems pointless, because the code inside the try is not going to throw any exceptions (except for system-level exceptions like OutOfMemoryException , but that's... exceptional, anyway).但是,在您的特定代码示例中, catch子句似乎毫无意义,因为try的代码不会抛出任何异常(除了像OutOfMemoryException这样的系统级异常,但无论如何,这是...例外)。 It would make more sense if there were a throw statement inside it, or a call to a method that you think might throw (for example, File.Open could throw a FileNotFoundException ).如果其中包含throw语句,或者调用您认为可能会抛出的方法(例如, File.Open可能会抛出FileNotFoundException ),这会更有意义。

Regarding code style, I would recommend that you use indentation a bit more:关于代码风格,我建议您多使用缩进:

public bool TestMethod()
{
    try
    {
        if (some_condition)
        { 
            //some random code
            return true;
        }
        else
        {
            return false;
        }
    }
    catch
    {
        return false;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM