2

I have a Scala method for which SonarLint (IntelliJ plugin version 3.2.1.2406) is flagging the return statement as 'Unreachable code'. For the purposes of this example I've removed the actual logic and replaced with printlns, but it produces the same issue. Note that debugging this shows that the return statement is in fact reachable.

def someMethod(): String = {
    try {
        println("Do something here")
    } finally {
        try {
            println("Do something else")
        } catch {
            case e: Exception => {
                println("Exception: " + e.getMessage)
            }
        }
    }
    return "Finished" // Sonarlint 'Unreachable code'
}

Additionally, removing the catch block results in the unreachable code issue disappearing.

Is this a bug in SonarLint? or am I missing something

Mike
  • 21
  • 2

1 Answers1

0

You need to put your "Finished" expression inside your Finally block. Your code is going to return either in the Try or Catch.

Example:

    def someMethod(): String = {
    try {
        println("Do something here")
    } finally {
        try {
            println("Do something else")
            "Finished"
        } catch {
            case e: Exception => {
                "Exception: " + e.getMessage
            }
        }
      }
    }

It'll return "Finished" or the exception.

Also using Return in Scala is redundant - just finish with the String.

  • Thanks for the reply - yes I have put the "Finished" inside the try in the actual code for now. However I still can't understand why it is considered unreachable, given that neither the try nor catch return anything. Also when debugging I can see it is actually returning "Finished". Regarding the return keyword, yes I realise it isn't required - I included for clarity because otherwise the sonarlint issue changes to something slightly different - ineffective operation or similar from memory. – Mike Mar 14 '18 at 13:35
  • "Your code is going to return either in the Try or Catch." not if the OP is correct that "debugging this shows that the return statement is in fact reachable." – The Archetypal Paul Mar 14 '18 at 14:11