第二篇:y异常处理
实验九 异常
实验目的:
1 了解异常概念,能熟练的使用try,catch,finally语句对异常进行处理。
2 能熟练的定义并使用自定义异常。
实验内容:
1 定义一个人类,包括姓名,性别,年龄,然后对年龄进行判断,如果不在年龄范围,抛出异常,并对其进行相应处理。
2 第七章实训任务。
实验结果:
第一题:
package hjn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GetPositiveInteger {
public static void main(String[] args) throws IOException {
String name;
int age;
boolean sex=false;
do{try{
System.out.println("请输入年龄:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
name=in.readLine();
age=Integer.parseInt(name);
if(age<=0 || age>=120){
throw new NegativeIntegerException();
}
sex=true;
}
catch(NumberFormatException e){
System.out.println("输入的年龄不符合规则,请重新输入。");
}
catch(NegativeIntegerException e){
System.out.println("输入的年龄不符合规则,请重新输入。");
}
}while(!sex);}
}
class NegativeIntegerException extends Exception{}
第二题:
package hjn;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GetPositiveInteger {
public static void main(String[] args) throws IOException {
String inputStr;
int inputNum;
boolean gotgoodInput=false;
do{
try{
System.out.println("请输入一个正整数:");
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
inputStr=in.readLine();
inputNum=Integer.parseInt(inputStr);
if(inputNum<=0){
throw new NegativeIntegerException();
}
gotgoodInput=true;
}
catch(NumberFormatException e){
System.out.println("输入的不是一个正整数,请重新输入。");
}
catch(NegativeIntegerException e){
System.out.println("输入的不是一个正整数,请重新输入。");
}
}while(!gotgoodInput);
}
}
class NegativeIntegerException extends Exception{}