java 自定义异常问题
import java.io.*;public class Person{
private String name;
private int age;
public Person(String name,int age)throws NameException,AgeException{
this.set(name);
this.set(age);
}
public void set(String name)throws NameException{
if(name==null||name=="1")
throw new NameException(name);
else
this.name=name;
}
public void set(int age)throws AgeException{
if(age>=0&&age<=100)
this.age=age;
else
throw new AgeException(age);
}
public static void main(String[] args){
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String str=in.readLine();
BufferedReader out=new BufferedReader(new InputStreamReader(System.in));
int i=Integer.parseInt(out.readLine());
try
{
Person p=new Person(str,i);
}
catch(NameException e)
{}
catch(AgeException e)
{}
finally
{
System.out.println(str+" "+i);
}
}
catch(IOException e){}
}
}
class NameException extends Exception{
public NameException(String name){
System.out.println("输入的名字不合法!");
}
}
class AgeException extends Exception{
public AgeException(int age){
System.out.println(age+"不在范围之内");
}
}
编译没有问题,但是无法捕抓异常--NameException
输入以下数据:
1
123
输出为:
123不在范围内
1 123