Try-catch v/s Null-check in Android.

I believe most of the productive developers are the lazy ones 🤣 . Most of us uses JSON2POJO , ButterKnife etc. to save time. No doubt , it’s good. But sometimes that laziness can slow down your app.

try-catch while parsing JSON

What we know about Try-catch ?

Once in an Interview with a fresher, I asked about try-catch and got funniest reply -

we put that code in try{} that we are afraid of it might be null or it can cause app crash & we catch error in catch{}.

But we can never catch Errors 😒 . Mostly newbies mistakenly takes Errors & Exceptions as same . Well , We were talking about Try-catch and Null Check.

In practice I see exception often used out of laziness. Instead of properly handling an error condition at the location where it occurs, people find it easier to throw an exception and catch it somewhere downstream, often resulting in spitting out some incomprehensible error message to the user.

Performance :

Clemens Vasters tweets some time ago -

Below we can see what happen when we write →

try{
   //some exception
}catch(Exception e){
e.printstacktrace();
//Log.e("",e.getMessage());
}
Taken from http://mattwarren.org/2016/12/20/Why-Exceptions-should-be-Exceptional/

Exceptions do take extra memory, as well as time, to catch. It is ALWAYS better to test for null if it’s a possible value. Another thing to consider it that it’s simply less code and more readable to do the null test. Usually having try/catch blocks adds essentially no overhead to your code for the normal case, but when the exception is triggered it’s quite expensive.

So what do we learned from above ? In one line -

Exceptions are, as their name implies, to be used only for exceptional conditions, they should never be used for ordinary control flow.

Moral ?

There are thousands cases where your code can go wrong: cannot connect to database, IO Exception, Network error… If you deal with them one by one (like the null check here), it would be too much of a hassle

but, if you know that variable/object can be null or it can cause a NullPointerException so better is to check rather than showing laziness (Ctrl+alt+t+6) 💻 (try-catch shortcut in Android Studio) 😜

Happy Coding.. 😈