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阻塞怎么办?
你有几个选择。
第一个选项是创建cmdavar并为其分配默认值或 null。当然,如果您设置为cmd可空,则需要在 try-catch 之后检查是否为空。(我推荐某种默认值,也许是EmptyCommandLine某种)。
第二个选项是使用 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)
| 归档时间: |
|
| 查看次数: |
1054 次 |
| 最近记录: |