# 上机练习题——异常处理

a<b<c

import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchTriangle {
public static void triangle(int a,int b,int c) throws IllegalArgumentException, InputMismatchException{
int[] s=new int[3];
s[0]=a;
s[1]=b;
s[2]=c;
Arrays.sort(s);
if((s[0]+s[1]>s[2])&&(s[2]-s[1]<s[0])){
System.out.println("三角形的三边长分别为"+a+","+b+","+c);
}
else{
throw new IllegalArgumentException();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int a=0,b=0,c=0;
Scanner in=new Scanner(System.in);
System.out.println("分别输入三角形的三边长：");
try {
a=in.nextInt();
b=in.nextInt();
c=in.nextInt();
triangle(a, b, c);

}catch(InputMismatchException e1){
System.err.println("三条边长必须是整数");
}
catch (IllegalArgumentException e2) {
// TODO: handle exception
System.err.println(a+","+b+","+c+"不能构成三角形");
}
}
}

import java.util.InputMismatchException;
import java.util.Scanner;
public class CatchArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
int a[]=new int[5];
System.out.println("请输入5个数作为数组元素:");
System.out.println("最后输入一个非数字结束输入操作。");
Scanner in=new Scanner(System.in);
try {
int i=0;
while(in.hasNextInt()){
a[i]=in.nextInt();
i++;
}
if(i>5){
throw new ArrayIndexOutOfBoundsException();
}
for(int j=0;j<a.length;j++){
System.out.print(a[j]+"");
}
}catch(InputMismatchException e1){
System.err.println("请输入整数！");
e1.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e2) {
// TODO: handle exception
System.err.println("请输入5个整数！");
e2.printStackTrace();
}finally{
System.out.println("感谢使用本程序！");
}
}
}




06-04 8683

08-16 2228
11-16 198
03-01 271
07-28 1万+
06-29 3610
08-17
07-29 160
11-16 150
11-04 244
08-16 3667
06-08 484
11-07 262
05-14 741
05-10 6957