Converting exceptions to null?

Is there an idiomatic way to run a piece of code and convert exceptions to null? Eg…

// Returns Number or throws
parse(str)
// Returns Number?
catchToNull { parse(str) }

I could write catchToNull easily enough. Just wondering if it’s already there under a different name.

1 Like

We have runCatching that would give you a Result. Maybe runOrNull would be a more kotlinesque name?

3 Likes
runCatching { parse(str) }.getOrNull()

Is the closest

5 Likes