That how we Catch ?: Errors !!

kotlin Jul 26, 2020

How to take advantage of try catch expression and null check to make error validation elegant.


tryOrNull | AndroidBites | Kotlin


TLDR 💻

Here is a snippet you can copy paste directly paste into your code base,

inline fun <T> tryOrNull(action:(Unit)->T):T? = {
  action.invoke()
} catch (e:Exception){
  Timber.w(e)// don't forget your error logging
  null
}
tryOrCatch extension

Now that's out of the way, You can enjoy the rest of the read! ☕️


It's a common practice to put any code which can throw an exception into a try-catch block. In Java it’s syntax pretty much looks like

try {  
	//statements that may cause an exception
} catch (Exception e) { 
	//error handling code
}
try catch in Java

You can’t return result from try or catch blocks so you need to use accumulator pattern to collect the result them, thus code would pretty much looks like

String runAway; // null

try {  
	runAway = escapeFromShip(); // Success or null
} catch (Exception e) {
	runAway = "" // failed
}

/*
 * ... later some code validation to check if the 
 * value of result is correct or not
/
Returning value from try catch in Java

This kind of flow makes lots of mutation points and validation to make sure our code is safe from crash. In Kotlin this flow is handled much more elegantly by treating try catch as expression not as block, and can be assigned to variable.

val runAway:String? = try {  
	escapeFromShip(); // Success or null
} catch (e:Exception) {  
	""	//failed
}
//.. validation for result is added later 
Returning value from try catch in Kotlin

Here accumulation problem is solved since last expression is returned from try catch block, but we still need to validate for right results, which can introduce lots of noise and ceremonial prone code.

Enjoying the Post?

a clap is much appreciated if you enjoyed. No sign up or cost associated :)

If you want to support my content do consider dropping a tip/coffee/donation💰

🤔 How to make Validation Fluent❓

If you have paid attention to Kotlin standard extension API they consist of function that are in form of getOrNull i.e they `return value or null`, which are on-spot name and design for what we want and works on the same principle.

If we consider null as an error state we can take advantage of Kotlin null check operators `!!` , `?:` to gracefully handling flow.

So , I can up with this extension :

inline fun <T> tryOrNull(action:(Unit)->T):T? = {
  action.invoke()
} catch (e:Exception){
  Timber.w(e)// don't forget your error logging
  null
}
tryOrCatch extension

Now let's see the fruits of your efforts! 🤩

val runAway:String? = tryOrNull { escapeFromShip() } //esape or fail 

val usingTheResut = result ?: ""

// or

result?.let{ //doSomthing }
tryOrNull example

That's all fokes 🐰🥕 ! See ya again in next post .. Happy Hacking 💻 .


Enjoying the Post?

a clap is much appreciated if you enjoyed. No sign up or cost associated :)

If you want to support my content do consider dropping a tip/coffee/donation💰




Chetan gupta

Hi there! call me Ch8n, I'm a mobile technology enthusiast! love Android #kotlinAlltheWay, CodingMantra: #cleanCoder #TDD #SOLID #designpatterns

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.