gpt4 book ai didi

Scala:如何简单地将相同的方法应用于 catch block 中的所有异常

转载 作者:行者123 更新时间:2023-12-04 01:13:42 24 4
gpt4 key购买 nike

考虑以下示例代码

try{
.....
}catch{
case e1:Exception1 => { method1(..)}
case e2:Exception2 => { method2(..)}
case e3:Exception3 => { method3(..)}
}

现在,如果我想对所有异常(e1e2e3)运行相同的方法,即 methodGeneral() )

但是如何避免像下面这样在每个 block 中应用该方法,而可以一次实现?

try{
.....
}catch{
case e1:Exception1 => { method1(..); methodGeneral();}
case e2:Exception2 => { method2(..); methodGeneral();}
case e3:Exception3 => { method3(..); methodGeneral();}
}

最佳答案

Scala Try 类型提供了比基本的 try..catch 更多的功能。例如,您可以这样做。

import scala.util.Try

Try {
. . .
}.recover{ excp:Throwable =>
excp match {
case e1:Exception1 => method1(..)
case e2:Exception2 => method2(..)
case e3:Exception3 => method3(..)
}
methodGeneral(excp)
}.get

这要求.recover 代码块返回与Try 代码块相同的类型。如果返回值实际上没有意义,例如 Unit,则可以省略 .get


如果您真的执着于旧的 try..catch,您可以尝试这样的方法。

try {
. . .
} catch {
case excp: Throwable =>
excp match {
case e1:Exception1 => method1(..)
case e2:Exception2 => method2(..)
case e3:Exception3 => method3(..)
}
methodGeneral(excp)
}

确保 try block 和 catch block 类型兼容仍然是个好主意。

关于Scala:如何简单地将相同的方法应用于 catch block 中的所有异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64038329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com