package test;
public class Testdate {
public static void main(String[] args) {
try{
int [] a = new int[3];
a[0] = 9;
a[1] =10;
a[2] = 12;
a[3] = 13;
for(int i = 0;i<a.length;i++){
System.out.println(a[i]);
if(i>3) throw new myException("下标越界");
}
}
catch(myException ee){
System.out.println("ljklkj");
System.out.println(ee.toString());
}
finally{
System.out.println("数组练习");
}
}
}
//
class myException extends Exception{
public myException(){
super();
}
public myException(String message){
super(message);
}
}
public class Testdate {
public static void main(String[] args) {
try{
int [] a = new int[3];
a[0] = 9;
a[1] =10;
a[2] = 12;
a[3] = 13;
for(int i = 0;i<a.length;i++){
System.out.println(a[i]);
if(i>3) throw new myException("下标越界");
}
}
catch(myException ee){
System.out.println("ljklkj");
System.out.println(ee.toString());
}
finally{
System.out.println("数组练习");
}
}
}
//
class myException extends Exception{
public myException(){
super();
}
public myException(String message){
super(message);
}
}
a[0] = 9;
a[1] =10;
a[2] = 12;
a[3] = 13;
这样初始化的是3个对象吧,就是a[0],a[1],a[2],访问a[3]就数组越界了。
a[0] = 9;
a[1] =10;
a[2] = 12;
a[3] = 13; 你申明一个长度为3的数组那你的下标就只有2(0,1,2)数组长度和下标是不同的
int [] a = new int[4];
这样才不会越界。
楼主是这意思么?
public class Testdate {
public static void main(String[] args) {
try{
int [] a = new int[4];
a[0] = 9;
a[1] =10;
a[2] = 12;
a[3] = 13;
for(int i = 0;i <=a.length;i++){
if(i>3) throw new myException("下标越界");
System.out.println(a[i]);
} }
catch(myException ee){
System.out.println("ljklkj");
System.out.println(ee.toString());
}
finally{
System.out.println("数组练习");
}
}
}
//
class myException extends Exception{
public myException(){
super();
}
public myException(String message){
super(message);
} }
这样估计可以看到你的异常处理.
package test;
public class Testdate {
public static void main(String[] args) {
try{
int [] a = new int[3];
a[0] = 9;
a[1] =10;
a[2] = 12;
a[3] = 13;
for(int i = 0;i <a.length;i++){
System.out.println(a[i]);
if(i>3) throw new ArrayIndexOutOfBoundsException("下标越界");
} }
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ljklkj");
System.out.println(e.toString());
}
finally{
System.out.println("数组练习");
}
}
} 输出:
ljklkj
java.lang.ArrayIndexOutOfBoundsException: 3
数组练习
至于为什么你所期望的异常没有执行是因为
程序在还没有到你写的异常的时候(在a[3] = 13就终止了),
系统就为你报了错误,他为你抛出数组下标越界的异常