import java.util.Scanner;
public class ExceptionTest1 {
void inputException()
{
int a[]=new int[3];
Scanner sc=new Scanner(System.in);
System.out.println(“请输入3个整型数据:”);
int i;
for(i=0;i<3;i++)
a[i]=sc.nextInt();
System.out.println(“a[“+i+”]=”+a[i]);
}
public static void main(String[] args) throws IllegalAccessException{
// TODO 自动生成的方法存根
ExceptionTest1 test=new ExceptionTest1();
try{
test.inputException();
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“数组越界 “+e);
}
finally
{
System.out.println(“最后一定会被执行的语句”);
}
}
}
运行结果:
知识点:
(1)异常的概念
(2)异常的分类
类Exception
构造方法:
public Exception();
public Exception(String s);
常用方法:
public String toString();
public void printStackTrace();
(3)异常的抛出
1)自动抛出异常
2)throw抛出异常
格式:返回类型 方法名(参数列表)throws 要抛出的异常类名列表 {
…
throws 异常类对象;
…
}
(4)异常的声明
格式:方法名()throws 要抛出的异常类名列表;
(5)异常的捕获和处理
1)try语句
try {
语句1
…
语句n
}
2)catch语句
catch(异常类型1,异常类型e1){
…
catch(异常类型2,异常类型e2){
…
catch(异常类型3,异常类型e3){
…
}
…
3)finally语句
finally {
语句1
…
语句n
}