zinking
zinking

Reputation: 5685

how to catch dynamically specified exception

Background is I have multiple exceptions I want to try on. can those be dynamically specified ?

def retryOn(e:Class[_])(n: Int)(block:() => Unit):Unit = {
    try {
        block()
    } catch {
        case e1: Throwable =>
            if (n > 1 && e1.isInstanceOf[e.type]) {
                retryOn(e)(n - 1)(block)
            }
            else throw e1
    }
}

from what tried above, this does not work, because the thrown e1 doesn't have any debug or type information at all.

Upvotes: 0

Views: 616

Answers (1)

Robin Green
Robin Green

Reputation: 33033

e.type is Class, so e1.isInstanceOf[e.type] does not do what you want. You need e.isInstance(e1) instead there.

Upvotes: 2

Related Questions