Never crash without try-catch

Huthefa Alfararjeh
2 min readDec 7, 2020

بسم الله و الحمد لله و الصلاة والسلام على رسول الله

How we make our android application safe from any crash?

an easy task, we can put every method logic in a try-catch block and we have done!

ok, but If we use try-catch everywhere how we know if the crash happened, so we fix it later?

an easy task,

we will log the crashes if an exception happens

so you have two thing

  1. Never crash
  2. you still know if any exception or crash

Ok, but if your manager asks you to show a simple toast(message box) when an exception happens?

here problems come to you

you have to change 1000 methods until you loop on the try-catch block

this happens because you violate (DRY principle ) do not repeat your self

1.try-catch block make code looks ugly

  1. you make your good ugly
  2. if you have a custom logic when the crash happens you have to change a lots
  3. if you want your app to crash again you will extract try-catch again

4.you can think more of these problems …, but these enough to cancel the idea

Solution 2:

what if we have a box that takes your function and call it in a try-catch block

fun <T> safeCall(block: () -> T) {
try {
block()
} catch (e: Exception) {
//here easy to run any common logic
if (BuildConfig.DEBUG)
Toasty.error(context, e.message.toString()).show()
//log to firebase
}
}

Now

fun tast() {
safeCall {
//you can do anything here
//that make compiler not happy
//but the compiler will be happy
}
}

this way you avoid a lot of crashes that do not break the app flow like (hide a dialog after closing current activity …)

--

--