Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 924
goo Avatar asked Jan 14 '14 22:01

goo


3 Answers

I think I would look to :

def something(x: Int, y:Int) = if ( y != 0) x/y else 0
like image 185
guest Avatar answered Oct 31 '22 07:10

guest


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
like image 40
senia Avatar answered Oct 31 '22 07:10

senia


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
like image 4
Brian Avatar answered Oct 31 '22 07:10

Brian