2017-07-18 164 views
-2

背景

我正在抛光我的Java版本,准备参加Oracle Java 8考试,并且遇到了一些令人费解的问题。我有一些基本的东西就是这样,它假定将作为参数的两个值传递:这抛出了哪个异常?

public static void main(String[] args) { 
    try { 
     String val1 = args[0]; 
     String val2 = args[1]; 
     ... 
    } catch (Exception e) { // <-- Here is where it gets tricky 
     ... 
    } 
} 

我意识到这是不好的形式赶上Exception,但是,当我通过在坏数据,我获得两个不同的具体例外情况,这取决于我对通用对象所做的操作,所以我不知道我需要在这里捕捉哪些内容。

设置

如果我这样做:

} catch (Exception e) { 
    System.err.println(e.toString()); 
} 

我得到一个java.lang.ArrayIndexOutOfBoundsException,这是有道理的,因为args是一个数组。

但是,如果我这样做,而不是:

} catch (Exception e) { 
    System.err.println(e.getCause().getMessage()); 
} 

我得到一个java.lang.NullPointerException 这也有道理,因为有一个String对象的引用在 args是不是有 这不有意义了,因为应该是是一个原因。

问题

哪些异常应该在这里抛出?

+0

这可能会抛出一个ArrayIndexOutOfBoundsException,因为您可能没有传递足够的参数 – ZeldaZach

+0

由于e.getCause()为空,您可能会得到一个新的'NullPointerException'。 – khelwood

+0

@Chris不,忘记'Integer.parseInt()'部分。当我不给程序任何参数时是个例外。我会编辑出来,以显示我真正要求的。 –

回答

1

尝试修改该方法如下面和调试,一步一步: -

public static void main(String[] args) { 
    try { 
     String val1 = args[0]; 
     String val2 = args[1]; 
    } catch (Exception e) { // <-- Here is where it gets tricky 
     System.err.println(e.toString()); 
     Throwable thr = e.getCause(); 
     String msg = thr.getMessage(); 
     System.err.println(msg); 
    } 
} 

从try子句引发的唯一的例外是ArrayIndexOutOfBoundsException异常。

在catch子句中,您会发现e.getCause()返回null,因为ArrayIndexOutOfBoundsException没有其他因果异常。

因此,当您尝试在空原因上调用getMessage()时,您将得到NullPointerException。