Scala: Divide by zero

I have something like this in my application:

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

    (x / y)
}

Now, if someval is not a number (this means that x or y is 0), then I would like Z to just become 0 instead of displaying an error ( [ArithmeticException: Division by zero])

I know that I can:

Try(someVale) orElse Try(0)

However, this will give me Success(0), whereas I just would like to give me 0in this case.

Maybe there is something like if ArithmeticException then 0in Scala or something to remove the “Success” and parentheses. Can someone shed some light please?

+4
source share
3 answers

, " " - , . , .

getOrElse Try orElse:

def something(x: Int, y: Int) = Try(x/y).getOrElse(0)

ArithmeticException, recover get:

def something(x: Int, y: Int) =
  Try(x/y).recover{ case _: ArithmeticException => 0 }.get

get , Try - Failure, recover Failure Success.

Try Option, " ", :

def something(x: Int, y: Int): Option[Int] = Try(x/y).toOption
+12

, :

def something(x: Int, y:Int) = if ( y != 0) x/y else 0
+12

Just catch the exception, and returning 0 is the easiest 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
+4
source

All Articles