3

I have a code which looks like this:

try {
    if (resp.equals("a")) {
       success(resp);
   } else if (resp.equals("b")) {
       throw new Exception("b error");
   } else if (resp.equals("c")) {
       throw new Exception("c error");
   }

} catch (Exception e) {
    dosomething(e.getMessage());
}

My catch statement doesn't catch the error... I'm I doing something wrong when I throw the exception that gets outside the try block?

danielrvt-sgb
  • 1,118
  • 5
  • 17
  • 33
  • 2
    you should read [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java), to understand why the code probably doesn't even throw the exception – jlordo Feb 13 '13 at 18:38
  • nope, I'm working with blackberry java, don't know if that can be an issue. But the exceptions I throw won't get caught... – danielrvt-sgb Feb 13 '13 at 18:48
  • 3
    Try adding an `else` block, and see if it gets executed. Also, print the value of `resp`, before the if-else blocks, to see that it contians. – Rohit Jain Feb 13 '13 at 18:51
  • You didn't say what is being thrown (-1 for that), but `catch (Exception e)` only catches Exceptions, not Errors. – Hot Licks Feb 13 '13 at 19:33
  • what is the value of `resp`? You know that `equals` is case-sensitive. – Ankit Feb 13 '13 at 19:39

6 Answers6

3

None of your if-else block will be executed, because you are comparing strings using == in all of them. In which case, the try block will not throw any exception at all.

Use equals method to compare string in all cases:

if (resp.equals("a"))

or:

if ("a".equals(resp))   // Some prefer this, but I don't

The 2nd way will avoid NPE, but generally I avoid using this, since I wouldn't know about the potential exception, and may fall in a trap later on.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • or even better `if("a".equals(resp))` to avoid potential `NullPointerException` when `resp` is `null`. – AlexR Feb 13 '13 at 18:40
  • you always should compare like this `"a".equals(resp)`. I think it's clear why. – Bevor Feb 13 '13 at 18:41
  • @Bevor Even better, make sure there is no null string flying around in your code... – assylias Feb 13 '13 at 18:43
  • 3
    @AlexR, Bevor. Well, I won't prefer to compare that way, because I would rather want to get Exception, if there is an exceptional case, rather than engulping that, and following with the code as if nothing happened. Which may of course bring some surprises for me. – Rohit Jain Feb 13 '13 at 18:43
  • @RohitJain Completely agree. – assylias Feb 13 '13 at 18:43
  • Is this answer still relevant even though the question got changed to using `.equals`? – Amir Raminfar Feb 13 '13 at 19:18
  • @AmirRaminfar. See my comment on the OP question after the question got edited. And after the question got changed, none of the answer is relevant now. Let's see what's the actual problem. – Rohit Jain Feb 13 '13 at 19:20
2

Using your code from above, with the missing variables and an added "else" clause at the end of your if block (and some output to see what's going on) added like so:

String resp = "b";
boolean success;
try {
    if (resp.equals("a")) {
       System.out.println("in a");
    } else if (resp.equals("b")) {
       throw new Exception("b error");
    } else if (resp.equals("c")) {
       throw new Exception("c error");
    } else System.out.println("ended with no match");

} catch (Exception e) {
    e.printStackTrace();
}

I get the error thrown as expected if the value of String resp is either "b" or "c". I also get the printout of "in a" if the value of resp is "a".

You don't have an else clause on the end of yours, so if it does not match either a, b or c then it will exit the if/else block and do nothing. No exceptions will be thrown as it has not encountered any code which is throwing them.

Are you certain you have one of these values for your resp variable?

Penelope The Duck
  • 656
  • 1
  • 7
  • 16
2

I think the problem is most likely to be a resp that is not handled by the if-else structure. I put the code in a simple test program:

public class Test {

  public static void main(String[] args) {
    test("a");
    test("b");
    test("c");
    test("d");
  }

  private static void test(String resp) {
    System.out.println("Testing: " + resp);
    try {
      if (resp.equals("a")) {
        success(resp);
      } else if (resp.equals("b")) {
        throw new Exception("b error");
      } else if (resp.equals("c")) {
        throw new Exception("c error");
      }

    } catch (Exception e) {
      System.out.println("Caught: " + e.getMessage());
    }
  }

  private static void success(String resp) {
    System.out.println("Success");
  }

}

The output was:

Testing: a
Success
Testing: b
Caught: b error
Testing: c
Caught: c error
Testing: d

I got "Success" or an exception for any of "a", "b", or "c", but neither for "d". I suggest looking for cases in your program in which resp does not have one of the values you are handling.

Patricia Shanahan
  • 25,849
  • 4
  • 38
  • 75
1

Wild guess: the branch where you throw the exceptions are never run because you are comparing strings with == instead of equals.

If you add an

else {
    System.out.println("in else block???");
}

in you try block, you will see that in live...

assylias
  • 321,522
  • 82
  • 660
  • 783
0

Yes, you are doing something wrong. Don't compare strings with ==, use .equals

Amir Afghani
  • 37,814
  • 16
  • 84
  • 124
0

You are using Exceptions to control a condition. This is a bad practice and really you should use just if-else. So something like this:

   if (resp.equals("a")) {
       success(resp);
   } else if (resp.equals("b")) {
       dosomething("b error");
   } else if (resp.equals("c")) {
       dosomething("c error");
   }

You can also do some thing like

enum Foo {a,b,c}

And then do something cleaner like this

switch(Foo.valueOf(resp){ // throws an IllegalArgumentException if it isn't a, b, or c
  case a: ...
  case b: ...
  case c: ...
}

Hope this helps and makes you a better programmer.

Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • Though I agree with your first point that you should not use `try-catch` to control flow, but you should not really use `enums` to store `constants` that doesn't at all seem to be related. `enums` are after all `enumerated constants`. – Rohit Jain Feb 13 '13 at 18:55
  • @RohitJain If there is a piece of code that is `if-elseif-elseif-else` then it really should be rewritten as a `case` statement for efficiency and readably. Java doesn't allow that yet with string comparison in `1.6` so I suggest using `Enum`s which is cleaner. It also give the programmer a quick insight on what all the different values are. – Amir Raminfar Feb 13 '13 at 19:16
  • I didn't comment about switch statement. I'm only saying that, `enum` usage here is not an ideal one. Since those strings may be unrelated values. Enums are generally prefered for enumerated values like - `Planets of solar system`, `Cards in a deck`, `Directions`, like this. – Rohit Jain Feb 13 '13 at 19:24
  • I see what you are saying. a,b,c are not really constants. I guess I did assume they are constants, or at least a set of known responses because it is a response that he is comparing to known values. For that reason, I think it would make sense. – Amir Raminfar Feb 13 '13 at 19:31