Search code examples
scaladivide-by-zero

Scala: Divide by zero


I have something like this in my app:

def something(x: Int, y: Int) Z {

    (x / y)
}

Now, if the someval is not a number (meaning that either x or y is equal to 0), then I'd like Z to just become 0 instead of displaying an error ([ArithmeticException: Division by zero])

I know I can do:

Try(someVale) orElse Try(0)

However, that'll give me Success(0) whereas I'd just like for it to give me a 0 in that case.

Maybe there's something like if ArithmeticException then 0 in Scala or something to remove the "Success" and parenthesis. Can someone shed some light please?


Solution

  • 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