尝试用Java编写的catch语句

时间:2015-07-20 19:56:14

标签: java try-catch illegalargumentexception

Java新手在这里,我正在尝试通过使用尽可能少的try ... catch语句来捕获抛出的异常。当我编译代码时,我收到了IllegalArgumentException个错误,并且不确定如何通过使用try ... catch语句来解决这个问题。

我看了教程,看过其他的例子,但由于这对我来说是一个新概念,我仍然不确定如何使用try ... catch进行这个特定的练习。

public class Main extends Object {

public static void main(String [] args) {
    tryGetMax();
    tryRemove();

private static final void tryGetMax() {
    int max = 0;
    max = FunMethods.getMax((Integer[])null);
    Integer[] numbers = new Integer[50];
    Random rand = new Random();
    for (int i = 0; i < 50; i++) {
        numbers[i] = new Integer(rand.nextInt(500));
    }
    numbers[32] = null;
    max = FunMethods.getMax(numbers);
    numbers[32] = new Integer(rand.nextInt(500));
    max = FunMethods.getMax(numbers);
}

练习的第二部分:

private static final void tryRemove() {
    FunMethods.remove(null, 2);
    Object[] someObjects = new Object[12];
    someObjects[0] = "a string!";
    someObjects[1] = new Integer(32);
    someObjects[2] = new Float(42.5f);
    someObjects[3] = "another string";
    for (int i = 4; i < someObjects.length; i++) {
        someObjects[i] = String.valueOf(i);
    }
    FunMethods.remove(someObjects, 12);
    someObjects = FunMethods.remove(someObjects, 3);

2 个答案:

答案 0 :(得分:0)

try{
  //Code that can potentially throw an exception
} catch (IllegalArgumentException e){
  //Code to run if exception is throw
}

将异常分配给变量e,该变量具有可以调用的某些方法。

答案 1 :(得分:0)

好的,就在你应该public static void main(String[] args) {的{​​{1}}下面try {。然后,在main方法的末尾,您应该有} catch (IllegalArgumentException e) {。在此之下,您应该拥有捕获该异常的代码,并}

现在这个:

public static void main(String [] args) {
    tryGetMax();
    tryRemove();

看起来像这样:

public static void main(String [] args) {
    try {
        tryGetMax();
        tryRemove();
    } catch(IllegalArgumentException e) {
        //this code runs if e is thrown
    }