编写一个类,在main方法中创建一个一维数组,使用try、catch、finally:
①在try块中,访问数组元素,使其产生ArrayIndexOutOfBoundsException异常。
②在catch块中,捕获此异常,并且打印“数组越界”信息。
③在finally块中,打印一条输出语句。
如有帮助,请采纳。点击我回答右上角【采纳】按钮。
public class MyMain{
public static void main(String[] args) {
int []nums={1,2,3};
try {
System.out.println(nums[3]);
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("数组越界");
}finally {
System.out.println("执行完毕!");
}
}
}
import java.util.Scanner;
public class Ex2
{
public static void main(String[] args)
{
System.out.println("\n\t\t==========输出异常信息!==========\n");
init();
}//初始化!
private static void init()
{
int[] arr=new int[2];
double a;
Test t=new Test();
System.out.println("输入一个数字");
while(true)
try
{
a=t.input();
int x=(int)a;
t.show(arr,x);
}
catch (TestException e)
{
System.out.println(e);
}
}
}
class TestException extends Exception
{
TestException(String name){super(name);}
}
class Test
{
void show(int[] arr,int index) throws TestException
{
if(index<0)
throw new TestException("数组下标异常");
if(index>=arr.length)
throw new TestException("数组溢出");
}
double input() throws TestException
{
double x=0;
try
{
double a=new Scanner(System.in).nextDouble();
x=a;
}
catch (Exception e)
{
throw new TestException("数字格式异常");
}
return x;
}
}