在 try/catch 之前初始化非空类型变量

Yar*_*Yar 1 java try-catch kotlin

假设我有这个代码块:

val cmd: CommandLine
try {
    cmd = parser.parse(options, args)
} catch (ex: ParseException) {
    // do stuff
}

// error: cmd is not initialized
val inputArg = cmd.getOptionValue("someArg")
Run Code Online (Sandbox Code Playgroud)

我收到错误是因为 cmd 未初始化,这是预期的,通常我会用nullJava 中的值初始化它,但是如果类型是non-null并且我不想将我的所有逻辑移动到try阻塞怎么办?

Aro*_*Aro 5

你有几个选择。

1) 你可以使用 var

第一个选项是创建cmdavar并为其分配默认值或 null。当然,如果您设置为cmd可空,则需要在 try-catch 之后检查是否为空。(我推荐某种默认值,也许是EmptyCommandLine某种)。

2) 更好的是,使用 try-catch 作为表达式

第二个选项是使用 try-catch 作为表达式,如下所示:

val cmd: CommandLine = try {
        parser.parse("options", "args")
    } catch (ex: Exception) {
        // Must:
        // 1) Throw, or error in some other way so as to return Nothing.
        // 2) Return a default/failed value for cmd. Maybe something like EmptyCommandLine or FailedCommandLine(ex)
        // 3) Make cmd nullable and return null.

        CommandLine() // or, error("Unable to parse options!")
    }

    val inputArg = cmd.getOptionValue("someArg")
}
Run Code Online (Sandbox Code Playgroud)

  • @Yar在这种情况下,您可以从 catch 块返回 null 并使“cmd”可为空。 (2认同)