package e;
import java.util.Scanner;
public class a {
static void inputException() throws myException{//抛出自定义异常
int a[]=new int[3];
Scanner sc=new Scanner(System.in);
System.out.println("请输入3个整型数据");
int i,sum=0,avg;
for(i=0;i<3;i++) {//输入3个元素质值
a[i]=sc.nextInt();
if(a[i]<0 || a[i]>100)//判断元素值是否在0-100之间,如果不在该范围内,则抛出自定义
throw new myException();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
try {//为方法Exception()进行监视
inputException();
}
catch(myException e) {//捕获异常,并输入错误提示
System.out.println("输入的数据需要在0-100之间("+e+")");
}
finally {//最终处理,输出相应信息提示
System.out.println("最后一定会被执行");
}
}
}
class myException extends Exception{//自定义异常
public String toString() {
return "自定义的异常";
}
}
结果:
知识点:1.掌握抛出异常的定义,以防出现不能执行时的情况