刚学JAVA第五章异常,前面就学了面向对象编程概念性的东西,题目是:编写程序 CustomException,在其中同时给出两个不同大小的数字型数组:{4,8,15,32,64,127,256,512}和 {2,1,2,4,4,48,8}.利用循环,将第一个数组包含的数字作为除数,第二个数组包含的数字作为被除数。用第一个数组中的数字除以第二个数组中相应位置的元素。当结果不是偶数或结果是除数本身此程序要抛出自定义异常,并捕获和处理相关的异常。提示:1.自定义 两个异常 2.ArrayIndexOutOfBoundsException类 public class CustomException {
public static void main(String []args){
int result;
int num[] = {4,8,32,64,127,256,512};
int num1[] = {2,1,2,4,4,4,8,8};
for(int i = 0; i<8; i++){
for(int j = 0; j<8; j++){
result = num[i]/num1[j];
}
}
try{
check();
}catch(MyException1 a){
System.out.println("第一个CATCH")
}catch(MyException2 b){
System.out.println("第二个CATCH");
}
public void check() throws ArrayIndexOutOfBoundsException{
if((result%2)!= 0){
throw new MyException1("aaaaaaaaaaa");
}
}
}
}public class MyException1 extends ArrayIndexOutOfBoundsException{
MyException1(){
System.out.println("1111111111");
}
} public class MyException2 extends ArrayIndexOutOfBoundsException{
MyException2(){
System.out.println("22222222222");
}
}
public static void main(String []args){
int result;
int num[] = {4,8,32,64,127,256,512};
int num1[] = {2,1,2,4,4,4,8,8};
for(int i = 0; i<8; i++){
for(int j = 0; j<8; j++){
result = num[i]/num1[j];
}
}
try{
check();
}catch(MyException1 a){
System.out.println("第一个CATCH")
}catch(MyException2 b){
System.out.println("第二个CATCH");
}
public void check() throws ArrayIndexOutOfBoundsException{
if((result%2)!= 0){
throw new MyException1("aaaaaaaaaaa");
}
}
}
}public class MyException1 extends ArrayIndexOutOfBoundsException{
MyException1(){
System.out.println("1111111111");
}
} public class MyException2 extends ArrayIndexOutOfBoundsException{
MyException2(){
System.out.println("22222222222");
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货