class Throwablethree{
/*//两种方式的写法
public static void main(String[] agrs) Exception {
Person p =new Person();
p.setAge(500);
*/
public static void main(String[] agrs){
Person p =new Person();
//处理异常
try{
p.setAge(900);
}
catch(AgeBIgException e){
e.printlnError();
}
catch(AgeSmallException e){
e.printlnError();
}
catch(AgeinvaException e){
e.printlnError();
}
}
}
//使用异常
class Person{
private int age;
public int getAge(){
return age;
}
public void setAge(int age) throws AgeBIgException,AgeSmallException,AgeinvaException{
if (age > 200){
throw new AgeBIgException();
}
else if (age == 0){
throw new AgeSmallException();
}
else if (age < 0){
throw new AgeinvaException("年龄非法");
}
this.age =age;
}
}
class AgeinvaException extends Exception{
private String info;
//构造函数第一条语句默认是super,就得调用父类的空构造
public AgeinvaException (String info ){
this.info =info;
}
public void printlnError(){
System.out.println(info);
}
}
//定义异常类继承AgeinvaException
////构造函数第一条语句默认是super,就得调用父类的空构造.上面有参数了,所以
//年纪太大太大异常
class AgeBIgException extends AgeinvaException{
public AgeBIgException (String info){
super(info);
}
public AgeBIgException (){
this("年纪太大");
}
}
//年龄太小异常
class AgeSmallException extends AgeinvaException{
public AgeSmallException (String info){
super(info);
}
public AgeSmallException (){
this("年纪太小");
}
}
--------------------------------------------------------------------------------------
作业:
一、
//定义三角形类Triangthroeb{a,b,c}
//两边之和大于第三边
//a b c 大于0
二、
2.Person.setBirthday(year,month,day);
a.年份上1970-2018
b.月份上1-12
c.天 1-31
d.生日是否有效
第一题
--------------------------------------------------------------------
class Triangthroeb{
public static void main(String[] agrs) {
Person p = new Person();
try{
p.Person(1,1,3);
}
catch(TriangchaException e){
e.printlnError();
}
catch(TriangException e){
e.printlnError();
}
}
}
class Person{
private int a;
private int b;
private int c;
public int Person(int a,int b,int c) throws TriangchaException,TriangException{
if (a<0||b<0||c<0 ){
throw new TriangException("参数为负数");
}
else if (a+b < c ||a+c < b ||b+c < a){
throw new TriangchaException();
}
return a;
}
}
class TriangException extends Exception{
private String info;
public TriangException (String info){
this.info =info;
}
public void printlnError(){
System.out.println(info);
}
}
class TriangchaException extends TriangException{
public TriangchaException (String info){
super(info);
}
public TriangchaException(){
this("两边之和小于第三边");
}
}