Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java throwing exceptions inside try block [duplicate]

Tags:

java

exception

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?

like image 407
danielrvt-sgb Avatar asked Nov 01 '25 06:11

danielrvt-sgb


2 Answers

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.

like image 54
Rohit Jain Avatar answered Nov 03 '25 19:11

Rohit Jain


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?

like image 34
Penelope The Duck Avatar answered Nov 03 '25 21:11

Penelope The Duck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!