Scala: Divide by zero
I think I would look to :
def something(x: Int, y:Int) = if ( y != 0) x/y else 0
I'm assuming "divide by zero" is just an example and you can't avoid throwing an exception. When you can avoid throwing an exception you should do it like in this answer.
You could use getOrElse
method on Try
instead of orElse
:
def something(x: Int, y: Int) = Try(x/y).getOrElse(0)
In case you want to recover only on ArithmeticException
you could use recover
method and get
:
def something(x: Int, y: Int) =
Try(x/y).recover{ case _: ArithmeticException => 0 }.get
With method get
you'll get an exception if Try
is Failure
, but recover
allows you to convert Failure
to Success
.
You could also convert your Try
to Option
to return "no result" without showing exception:
def something(x: Int, y: Int): Option[Int] = Try(x/y).toOption
Just catch the exception and return 0 is the simplest way.
def something(x: Int, y: Int) = try {
(x / y)
} catch {
case ae: java.lang.ArithmeticException => 0
}
Run it:
scala> something(1,0)
res0: Int = 0
scala> something(2,1)
res1: Int = 2