qan99
qan99

Reputation: 15

Pattern matching a non-exceptional value using try-catch expression

I have a question regarding the try catch block .Here is an example :

val num = try {
  110 / 12
} catch {
  case ex: NumberFormatException => 0
}

val num1 = try {
  110 / 13
} catch {
  case a: num1 > 10 => 10
  case b: num1 < 10 => 12
}

I know num works so why is num1 not valid? All the examples and articles I've seen only do the NumberFormatException or ArithmenticException. And also are greater than and less than not valid operators in the case statement? Is it possible to treat the try catch block like an if else block using pattern matching?

Upvotes: 0

Views: 798

Answers (2)

som-snytt
som-snytt

Reputation: 39577

Supplementing the other answer, if you itch to have a tidy list of cases:

scala> import util._
import util._

scala> Try(1/0) match {
     | case Success(i) if i > 42            => 42
     | case ok @ Success(_)                 => ok
     | case Failure(_: ArithmeticException) => 27
     | }
res0: Int = 27

Upvotes: 1

Mario Galic
Mario Galic

Reputation: 48410

I guess you are attempting to write something like

try {
  110 / 13
} catch {
  case a if a > 10 => 10
  case b if b < 10 => 12
}

however this is not valid syntax because a try expression is of the form

try { b } catch h

where handler h must be a partial function of type

PartialFunction[Throwable, T]

so a in case a if a > 10 must be Throwable however Throwable does not have > method defined on it.


Consider monadic error handling using Try instead of try-catch expression. This would allow you to simply map over in the happy case. For example, consider

Try(110 / 13)
  .map(num => if (num > 10) 10 else 12)
  .getOrElse(someDefaultValue)

Handling Error Without Exceptions has some interactive exercises to get you started with the concept.

Upvotes: 4

Related Questions