throw与throws的区别和使用throw抛出异常

一、Throw和throws区别:

1、书写:throws定义在方法名上,throw定义在方法体内

2、作用:throws声明异常,throw抛出异常

3、语法:throws 异常类  throw 异常对象

4、Throws 异常类1,.....,异常n        throw 异常对象

二、用throw抛出异常,代码如下:

package ThrowDemo;

public class Person {    

    private int age;
    private String sex;
    
    public void Setsex(String sex)throws Exception{
    if(sex!="男" && sex!="女"){
    throw new Exception("性别必须为“男”或“女”!");
    }else{
    this.sex=sex;
    }
    }
    public void Setage(int age)throws Exception{
    if(age>=1 && age<=100){
    this.age=age;
    }else{
    throw new Exception("年龄必须在1到100之间!");
    }

    }

package ThrowDemo;
public class ThrowException {
public static void main(String[] args) {
             Person per=new Person();
             try{
             per.Setsex("男");
             per.Setage(111);
            }catch(Exception e){
             e.printStackTrace();
           }
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值