Sanjana Nair
Sanjana Nair

Reputation: 2785

Try/Catch with if conditions in Java/Android

I am trying to catch the exception and not allow the app to force close. Hence I am put the try and catch like the blow:

try 
{
  String[] words = message.split(" ");
  strBuilder.setLength(0);

  numberString = words[8];
  if (numberString.length() > 4) 
  {
    numberString = numberString.substring((numberString.length() - 4));
  } 

   if ((message.contains("return"))) 
   {
     amountString = words[0];
     amountString = amountString.replace(",", "");
     amountString = getFilter(message);
    }

   else 
    {
      for (int i = 12; i < words.length; i++) 
        {
         text = words[i];
         strBuilder.append(text + " ");
         str = strBuilder.toString();
        }

      amountString = words[1];
      amountString = amountString.replace(",", "");

      nameString = str;
    }

    Log.e("Value","= " + amountString + nameString + numberString);
} 
catch (NotFoundException e) 
{
   Log.e("ERROR","Value Not fetched");
}   

}

I am trying the above code in a for loop...

but the app still crashes and gives error in amountString = getFilter(message); Why is this happening?

Do I need to insert try and catch before amount=getFilter(message);?

Upvotes: 2

Views: 1047

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

You are only catching NotFoundException but there may be some other exception happening in your code execution that is crashing your app. So try catching Exception to find what is going wrong.

Upvotes: 3

Anubian Noob
Anubian Noob

Reputation: 13596

Look at your catch statement:

catch (NotFoundException e) {

You're only catching one exception, a NotFoundException. I'd check Logcat and see what exception is thrown, and catch that instead.

If you want a quick and dirty solution, you can catch Exception. But that will catch anything at all. If you have a random NullPointerException or NumberFormatException it'll be caught too, which could mask serious issues or make debugging difficult.

Upvotes: 1

Related Questions