Java新手在这里,我正在做一个练习,试图通过使用尽可能少的尝试来捕获抛出的异常…尽可能使用Catch语句。当我编译代码时,我收到了IllegalArgumentException
错误,不确定如何通过使用try…捕捉语句。
我看过教程,看了其他的例子,但因为这对我来说是一个新的概念,我仍然不确定如何使用的尝试…
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);
try{
//Code that can potentially throw an exception
} catch (IllegalArgumentException e){
//Code to run if exception is throw
}
异常被赋值给变量e
,该变量具有某些可以调用的方法
好的,在public static void main(String[] args) {
下面应该有try {
。然后,在主方法的末尾,您应该有} 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
}