Unreachable code, but reachable with an exception

how to fix unreachable code in java
how to remove unreachable code error in c++
unreachable code exception in java
unreachable code java
unreachable code error python
how to fix unreachable statement in java
unreachable code pylint(unreachable)
unreachable code after return statement java

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 successfully created, then returning true.

My understanding of control flow is as follows:

command.ExecuteNonQuery() is documented to throw an Invalid​Operation​Exception when "a method call is invalid for the object's current state". Therefore, if that would happen, execution of the try block would stop, the finally block would be executed, then would execute the return false; at the bottom.

However, my IDE claims that the return false; is unreachable code. And it seems to be true, I can remove it and it compiles without any complaints. However, for me it looks as if there would be no return value for the code path where the mentioned exception is thrown.

private static bool createRecord(String table,
                                 IDictionary<String,String> data,
                                 System.Data.IDbConnection conn,
                                 OdbcTransaction trans) {

    [... some other code ...]

    int returnValue = 0;
    try {
        command.CommandText = sb.ToString();
        returnValue = command.ExecuteNonQuery();

        return returnValue == 1;
    } finally {
        command.Dispose();
    }

    return false;
}

What is my error of understanding here?

Unreachable Code Error in Java, Any statement after throwing an exception: If we add any statements in a try-catch block after throwing an exception, those statements are� 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 successfully created, then returning true. My understanding of control flow is as follows: command.ExecuteNonQuery() is documented to

the finally block would be executed, then would execute the return false; at the bottom.

Wrong. finally doesn't swallow the exception. It honors it and the exception will be thrown as normal. It will only execute the code in the finally before the block ends (with or without an exception).

If you want the exception to be swallowed, you should use a catch block with no throw in it.

Unreachable code, In computer programming, unreachable code is part of the source code of a program which can thereby making the corresponding code unreachable, but which can occur in other runtime environments, for The following exceptions are often mistakenly categorized as dead code but are necessary for implementation of� The last statement return false is unreachable, because the try block is missing a catch part that would handle the exception, so the exception is rethrown after the finally block and the execution never reaches the last statement.

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 { ... }

Is throwing new RuntimeExceptions in unreachable code a bad style , I'm curious if throwing RuntimeException("cannot reach here") is justified. I'm probably missing something obvious knowing that this piece of code comes from � The definition int Z = X * Y; is never reached as the function returns before the definition is reached. Therefore, the definition of Z can be discarded.. goto fail bug. An example of real life code that contained a major security flaw due to unreachable code is Apple's SSL/TLS bug formally known as CVE-2014-1266 and informally known as the "goto fail bug" from February 2014.

It seems, you are looking for something like this:

private static bool createRecord(string table,
                                 IDictionary<String,String> data,
                                 System.Data.IDbConnection conn,
                                 OdbcTransaction trans) {
  [... some other code ...]

  // Using: do not call Dispose() explicitly, but wrap IDisposable into using
  using (var command = ...) {
    try {
      // Normal flow:
      command.CommandText = sb.ToString();

      // True if and only if exactly one record affected
      return command.ExecuteNonQuery() == 1;
    }
    catch (DbException) {
      // Exceptional flow (all database exceptions)
      return false;
    }
  }
}

Please, note, that finally doesn't swallow any exception

finally {
  // This code will be executed; the exception will be efficently re-thrown
}

// And this code will never be reached

Unreachable code - Python queries, However, it is possible that the original intention was that the code should execute and that it is unreachable signifies some other error. Example. Unreachable code, but reachable with an exception (6) 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 successfully created, then returning true.

You don't have a catch block, so the exception is still thrown, which blocks the return.

the finally block would be executed, then would execute the return false; at the bottom.

This is wrong, because the finally block would be executed, and then there would be an uncaught exception.

finally blocks are used for cleanup, and they do not catch the exception. The exception is thrown before the return, therefore, the return will never be reached, because an exception is thrown before.

Your IDE is correct that it will never be reached, because the exception will be thrown. Only catch blocks are able to catch exceptions.

Reading from the documentation,

Usually, when an unhandled exception ends an application, whether or not the finally block is run is not important. However, if you have statements in a finally block that must be run even in that situation, one solution is to add a catch block to the try-finally statement. Alternatively, you can catch the exception that might be thrown in the try block of a try-finally statement higher up the call stack. That is, you can catch the exception in the method that calls the method that contains the try-finally statement, or in the method that calls that method, or in any method in the call stack. If the exception is not caught, execution of the finally block depends on whether the operating system chooses to trigger an exception unwind operation.

This clearly shows that the finally is not intended to catch the exception, and you would have been correct if there had been an empty catch statement before the finally statement.

Java 8 Unreachable code produces warning not error, This code has an unreachable catch block and the Java compiler does not produce statement in the try block is reachable and can throw a checked exception� Unreachable code is never executed. The C# compiler issues an unreachable code detected warning. The C# compiler issues an unreachable code detected warning. This warning can help you eliminate unused code.

C# Unreachable Code Detected, Understand and fix the unreachable code detected compiler warning. { while ( false) { int value = 1; if (value == 2) { throw new Exception(); } } } } Warning: Warning Reachability in the C# language is carefully described in the specification. Any statement after throwing an exception: If we add any statements in a try-catch block after throwing an exception, those statements are unreachable because there is an exceptional event and execution jumps to catch block or finally block. The lines immediately after the throw is not executed.

UnreachableCodeException, Details: An UnreachableCodeException may be thrown whenever an execution path that has assumed to be unreachable actually turns out to be reachable. However, since you are safety-conscious, your code might look like this: if we actually get here! throw new UnreachableCodeException("Surprise, you moron! When the compiler (back end) detects unreachable code, it will generate C4702, a level 4 warning. For code that is valid in both the Visual Studio .NET 2003 and Visual Studio .NET versions of Visual C++, remove the unreachable code or assure that all source code is reachable by some flow of execution. Example. The following sample generates C4702.

MSC12-C. Detect and remove code that has no effect , Code that has no effect or is never executed (that is, dead or unreachable code) is typically the result of a coding error and can cause unexpected behavior. Unreachable code, a part of the source code that will never be executed due to inappropriate exit points/control flow. The other kind of unreachable code is referred as dead code, although dead code might get executed but has no effect on the functionality of the system.

Comments
  • docs.microsoft.com/en-us/dotnet/csharp/language-reference/…
  • Side note: do not call Dispose explicitly, but put using: using (var command = ...) {command.CommandText = sb.ToString(); return command.ExecuteNonQuery(); }
  • A finally block means something else than you think.
  • What do you mean by IL in the first sentences?
  • @Clockwork IL is a product of compilation of code written in high-level .NET languages. Once you compile your code written in one of these languages, you will get a binary that is made out of IL. Note that Intermediate Language is sometimes also called Common Intermediate Language (CIL) or Microsoft Intermediate Language (MSIL).,
  • In short terms, because he didn't catch the possibilities are: Either the try runs until it hits return and thus ignores the return below finally OR an exception is thrown and that return is never reached because the function will exit due to an exception being thrown.
  • will the above sinppet compile in case exception, what will be returned?
  • It does compile, but it will never hit return false since it will throw an exception instead @EhsanSajjad
  • seems strange, compiles because either it will return a value for bool in case of no exception and in case of exception nothing will be, so legit for to satisfy method's return type ?
  • The compiler will just ignore the line, that is what the warning is for. So why is that strange? @EhsanSajjad
  • Fun fact: It is actually not guaranteed that a finally block will run if the exception is not caught in the program. The spec doesn't guarantee this and early CLRs did NOT execute the finally block. I think starting with 4.0 (might have been earlier) that behavior changed, but other runtimes might still behave differently. Makes for rather surprising behavior.