Java在try块中抛出异常

时间:2013-02-13 18:37:24

标签: java exception

我有一个代码如下:

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());
}

我的catch语句没有捕获错误...当我抛出超出try块的异常时,我做错了什么?

6 个答案:

答案 0 :(得分:3)

您的if-else块都不会被执行,因为您在所有块中使用==比较字符串。在这种情况下,try块不会抛出任何exception

在所有情况下使用equals方法比较字符串:

if (resp.equals("a"))

或:

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

第二种方式将避免使用NPE,但通常我会避免使用此方法,因为我不知道潜在的异常,并且可能会在以后陷入陷阱。

答案 1 :(得分:2)

使用上面的代码,在if块的末尾添加缺少的变量和添加的“else”子句(以及一些输出以查看正在发生的事情),如下所示:

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();
}

如果String resp的值为“b”或“c”,则会按预期抛出错误。如果resp的值为“a”,我也会得到“in a”的打印输出。

你的末尾没有else子句,所以如果它与a,b或c都不匹配,那么它将退出if / else块而不执行任何操作。没有异常将被抛出,因为它没有遇到任何抛出它们的代码。

你确定你的resp变量有这些值之一吗?

答案 2 :(得分:2)

我认为问题最有可能是if-else结构无法解决的问题。我把代码放在一个简单的测试程序中:

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");
  }

}

输出结果为:

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

我得到“成功”或“a”,“b”或“c”中的任何一个例外,但“d”都没有。我建议在你的程序中查找resp没有你正在处理的值之一的情况。

答案 3 :(得分:1)

狂野猜测:抛出异常的分支永远不会运行,因为您要将字符串与==而不是equals进行比较。

如果添加

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

在你尝试阻止时,你会在现场看到......

答案 4 :(得分:0)

是的,你做错了什么。不要将字符串与==进行比较,请使用。equals

答案 5 :(得分:0)

您正在使用Exception来控制条件。这是一种不好的做法,你应该只使用if-else。所以像这样:

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

你也可以做一些像

这样的事情
enum Foo {a,b,c}

然后做一些像这样清洁的事情

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

希望这会有所帮助并使您成为更好的程序员。

相关问题