几道JAVA题求解!急~~~~~~

2025-05-19 18:02:49
推荐回答(1个)
回答(1):

第一题:

public class ExArray1

       public static void main(String[] args)
       {
              int[] []t={{1,2,3},{4,5}};          
              try
              {    
                     System.out.print(t[1][2]);
              }
              //错误原因:catch必须紧跟try语句块
              //System.out.print("after try block");
              catch (Exception e)
              {
                  System.out.print(e.toString());
              }
              System.out.print("Error");
           }
}

运行效果:

java.lang.ArrayIndexOutOfBoundsException: 2Error


第二题:

public class ExArray2 {
public static void main(String[] args) {
int[][] t = { { 1, 2, 3 }, { 4, 5 } };

try {
System.out.print(t[1][3]);
} catch (Exception e) {
System.out.println("程序出现了数组下标越界异常");
}
}
}

    效果:

    程序出现了数组下标越界异常

第二题,第二个要求:

public class ExArray2 {
public void test() throws ArrayIndexOutOfBoundsException {
int[][] t = { { 1, 2, 3 }, { 4, 5 } };
System.out.print(t[1][3]);
}

public static void main(String[] args) {
ExArray2 array2 = new ExArray2();
try {
array2.test();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("程序出现了数组下标越界异常");
}
}

}

    效果同第一个。


第三题:(请看注释区域)

public class TryCatchFinally1 {
public static void main(String args[]) {
// 调用可能产生异常的方法Proc()
try {
TryCatchFinally1.Proc(0);
TryCatchFinally1.Proc(1);

}
// 捕获异常,并对异常进行处理
catch (ArithmeticException e) {
System.out.println("捕获:" + e + "; 理由:" + e.getMessage());
} catch (Exception e) {
System.out.println("Will not be executed");
}
}

// 定义可能产生异常的Proc()方法,并声明异常
static void Proc(int sel) throws ArithmeticException {
System.out.println("----- 在为" + sel + "情况下 -----");
if (sel == 0) {
System.out.println("没有异常捕获");
} else if (sel == 1) {
int i = 0;
/**
 * 在这里出现了异常,也就为1的情况下,除数为0了
 * 
 * 而Proc这个方法并没有对异常进行处理,只是又抛了出去
 * 
 * 所以就在调用的时候对异常进行了处理
 * 
 * 也就是main方法里对这个方法的调用
 */
int j = 4 / i;
}
}
}

    第四题:

public class TestException {
public static int[] arr=new int[]{2,0}; 
public static void main(String args[]) {
TestException.Proc(0);
TestException.Proc(1);
}

public static void Proc(int i){
if(i==0){
try {
System.out.println(arr[2]);
} catch (ArrayIndexOutOfBoundsException e) {
//数组越界
System.out.println("捕获:"+e+";"+"理由:"+e);
}
}else if(i==1){
try {
System.out.println(arr[0] / arr[1]);
} catch (ArithmeticException e) {
//数学运算错误
System.out.println("捕获:"+e+";"+"理由:"+e);
}
}
}
}

    效果:

    

捕获:java.lang.ArrayIndexOutOfBoundsException: 2;理由:java.lang.ArrayIndexOutOfBoundsException: 2

捕获:java.lang.ArithmeticException: / by zero;理由:java.lang.ArithmeticException: / by zero



    希望能帮到你,望采纳。