首页 > 解决方案 > 如何在 java 中修复“未能抛出 IllArgumentException”

问题描述

我正在尝试编写一个程序,对两个整数的列表进行排序,以便元素按升序排列,列表的大小保持不变,如果列表的大小不等于 2,则给出 IllegalArgumentException。

这就是我所拥有的:

public static void sort2(List<Integer> t) { //t is a the list
        if(t.size() < 3) {
            Collections.sort(t);
            System.out.println(t);
        }
        else if (t.size() == 2) {
            throw new IllegalArgumentException("List is empty");
        }
}

但是,当我进行 JUnit 测试时,排序通过,但异常测试失败。测试如下:

public void test10a_sort2() {
    ArrayList<Integer> t = new ArrayList<>();
    String error = "lab0.sort2(t) failed to throw an IllegalArgumentException";
    try {
      lab0.sort2(t);
      fail(error);
    }
    catch (IllegalArgumentException x) {
      // do nothing
    }
    catch (Exception x) {
      fail("lab0.sort2(t) threw the wrong kind of exception");
    }

    t.add(1);
    try {
      lab0.sort2(t);
      fail(error);
    }
    catch (IllegalArgumentException x) {
      // do nothing
    }
    catch (Exception x) {
      fail("lab0.sort2(t) threw the wrong kind of exception" + x);
    }

    t.add(2);
    t.add(3);
    try {
      lab0.sort2(t);
      fail(error);
    }
    catch (IllegalArgumentException x) {
      // do nothing
    }
    catch (Exception x) {
      fail("lab0.sort2(t) threw the wrong kind of exception");
    }
  }

不太确定我做错了什么。我也尝试使用 try catch,但似乎效果不佳。

标签: javaexception

解决方案


    if(t.size() < 3) {
        // ...
    }
    else if (t.size() == 2) {
        throw new IllegalArgumentException("List is empty");
    }

只有当第一个条件为假且第二个条件为真时,您才会抛出异常,即t.size() >= 3 && t.size() == 2. 这显然是不可能的,所以永远不会抛出异常。


把抛出异常的条件放在前面:

if (t.size() != 2) {
  throw ...
}

如果大小是2之后再放东西。


推荐阅读