从Kotlin中的Try/Catch块返回



Kotlin新手在这里…

我有一个返回userDefined对象的方法

fun doSomethingMagical(param1: String): UserDefinedObject {
val result = UserDefinedObject
// execute some code 
try {
....
if(some expression){
val temp = //some code
result = temp
}
return result
} catch(e : Exception){
null
}
}

上面的方法给了我两个错误:

变量'result'必须初始化

具有块体('{…}')的函数所需的'return'表达式

欢迎任何帮助!

这里有一个解决方案,但可能不是最好的:

fun doSomethingMagical(param1: String): UserDefinedObject? {
var result = UserDefinedObject() 
//assuming this object has no properties
//if it does you much provide them to initialize it
...
try {
....
if(some expression){
val temp : UserDefinedObject = //some code
result = temp
} catch(e : Exception){
return null
}
return result
}

一个更好的,取决于你是否需要在尝试之前的结果(我假设你不需要),你可以这样做:

fun doSomethingMagical(param1: String): UserDefinedObject? {
return try {
whateverSomeCodeIs() // returns a UserDefinedObject
} catch(e : Exception){
null
}
}

或者这样:

fun doSomethingMagical(param1: String): UserDefinedObject? {
try {
return whateverSomeCodeIs() // returns a UserDefinedObject
} catch(e : Exception){
return null
}
}

或者用这种方式暗示返回类型,而不需要"return"明确:

fun doSomethingMagical(param1: String) = try { whateverSomeCodeIs() } catch(e: Exception) { null }

如果你不想让它为空(也就是"?"指示),那么你需要在catch中返回UserDefinedObject,允许抛出异常并稍后捕获它,或者确保异常不能被抛出。

我还建议您查看Kotlin文档。它们信息量很大。这里有一个到他们的Exceptions部分的链接。

那么一点背景-try块是你包装一些代码时,代码可能是throwException,你可以认为是一种错误。如果抛出异常,代码的执行停止,程序开始退出它调用的函数链以到达它所在的位置。如果没有catch出现异常,它最终会使程序崩溃。

因此,为了安全起见,您可以将代码包装在try块中(这意味着它可能会抛出),并添加catch块来处理预期的异常。如果抛出一个异常,它会退出try块,但如果有一个catch

处理该异常类型,它会跳转到该块并从那里继续执行——它被处理了,一切都可以继续!例如,如果您想从一个文件中读取,那么由于某种原因它不可用,读取代码可能会抛出IOException。您应该catch该异常类型,并优雅地处理这种情况,而不是让它崩溃之类的事情。

下面是代码的基本流程:
fun doSomethingMagical(param1: String): UserDefinedObject {
val result = UserDefinedObject
// execute some code 
try {
....
return result
} catch(e : Exception){
null
}
}

你基本上说的是,你要去try执行一些代码,最终以return语句结束。但这意味着有可能出现异常,提前结束该块—您可能永远不会命中return。在这种情况下,您跳转到catch块(处理所有类型的Exception),执行其中的任何操作,然后退出整个try/catch并继续执行doSomethingMagical函数的其余部分。

但如果发生这种情况,你永远不会击中return。如果抛出异常(您明确地说可能会通过使用try块发生-这是您说您将处理它),那么您将不会到达return语句-这就是为什么您会获得A 'return' expression required in a function with a block body或其他错误消息的原因。可能有一个执行流没有到达1,这是不允许的


所以有两种典型的方法来做到这一点-您可以在try中返回一个值,并在catch中返回一个回退值:

try {
...
// return from the function right here
return result
} catch(e: Exception) {
// or if there was a problem, return from here
return fallbackValue
}

或者只是用默认值初始化一个可变的var,在函数结束时返回它,并且可能在try中更改它(如果成功的话):

var result = someDefaultValue
try {
// do things, set new result
result = somethingElse
} catch (e: Exception) {
// whatever handling you need to do, having this here ensures code execution
// continues if there's any problem in the try block
}
// whatever the value of result is (default or if it's been changed), return it here
return result

后者看起来像你要去的,因为你在函数开始时初始化一个result值(如果你想改变它,不能是val)

最新更新