Unreachable code, but reachable with an exception

前端 未结 9 1706
说谎
说谎 2020-12-28 11:22

This code is part of an application that reads from and writes to an ODBC connected database. It creates a record in the database and then checks if a record has been succes

9条回答
  •  遥遥无期
    2020-12-28 11:45

    The warning is because you didn't use catch and your method is basically written like this:

    bool SomeMethod()
    {
        return true;
        return false; // CS0162 Unreachable code detected
    }
    

    Since you use finally solely to dispose, the preferred solution is to utilize using pattern:

    using(var command = new WhateverCommand())
    {
         ...
    }
    

    That's enough, to ensure what Dispose will be called. It's guaranteed to be called either after successful execution of code block or upon (before) some catch down in call stack (parent calls are down, right?).

    If it wouldn't be about disposing, then

    try { ...; return true; } // only one return
    finally { ... }
    

    is enough, since you will never have to return false at the end of method (there is no need for that line). Your method is either return result of command execution (true or false) or will throw an exception otherwise.


    Consider also to throw own exceptions by wrapping expected exceptions (check out InvalidOperationException constructor):

    try { ... }
    catch(SomeExpectedException e)
    {
        throw new SomeBetterExceptionWithExplanaition("...", e);
    }
    

    This is typically used to say something more meaningful (useful) to the caller than nested call exception would be telling.


    Most of times you don't really care about unhandled exceptions. Sometimes you need to ensure that finally is called even if exception is unhandled. In this case you simply catch it yourself and re-throw (see this answer):

    try { ... }
    catch { ...; throw; } // re-throw
    finally { ... }
    

提交回复
热议问题