[英]Scala "Try" return type and exception handling
I am a newbie for Scala and now am trying to complete an exercise.我是Scala的新手,现在正在尝试完成一个练习。 How can I return an InvalidCartException while the function return type is Try[Price]如何在 function 返回类型为Try[Price]时返回InvalidCartException
//Success: return the calculated price
//Failure: InvalidCartException
def calculateCartPrice(cart:Cart): Try[Price] = {
if(isCartValid(cart)) {
//Calculations happen here
return Try(Price(totalPrice));
}
}
def isCartValid(cart: Cart): Boolean = {
//THIS WORKS FINE
}
Thank you for the help感谢您的帮助
If you mean "how to make the Try
contain an exception" , then use the Failure()
like below:如果您的意思是“如何使Try
包含异常” ,请使用如下所示的Failure()
:
def calculateCartPrice(cart:Cart): Try[Price] = {
if(isCartValid(cart)) {
//Calculations happen here
Success(Price(totalPrice));
} else {
Failure(new InvalidCartException())
}
}
Then, given a Try
you can use getOrElse
to get the value of success or throw the exception.然后,给定一个Try
,您可以使用getOrElse
获取成功的值或抛出异常。
Try
will catch the exception for you, so put the code that can throw the exception in there. Try
会为你捕获异常,所以把能抛出异常的代码放在那里。 For example例如
def divideOneBy(x: Int): Try[Int] = Try { 1 / x}
divideOneBy(0) // Failure(java.lang.ArithmeticException: / by zero)
If what you have is a Try
and you want to throw the exception when you have a Failure
, then you can use pattern matching to do that:如果你有一个Try
并且你想在遇到Failure
时抛出异常,那么你可以使用模式匹配来做到这一点:
val result = divideByOne(0)
result match {
case Failure(exception) => throw exception
case Success(_) => // What happens here?
}
The Neophyte's Guide to Scala has lots of useful information for people new to Scala (I found it invaluable when I was learning). Neophyte's Guide to Scala 对刚接触Scala的人有很多有用的信息(我在学习的时候发现它非常宝贵)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.