异常处理2

package c;
//方法调用时的异常处理
/*public class Exceptions2 {
public static void main(String args[]){
    int x[]={2,5,9};
    try{
        div d=new div();
        d.meth();
        x[3]=100;
    }catch(ArithmeticException e){
        System.out.println("1");
    }catch(RuntimeException e){
        System.out.println("2");
    }catch(Exception e)
    {
        System.out.println("3");
    }
}
}
class div{
    void d(int a,int b){
        int s=0;
        s=a/b;
        System.out.println("商:"+s);
    }
    void meth()
    {
        d(18,2);
        d(3,0);
    }
}
//
/*
 商:9
1
在方法d()中并没有捕获和处理异常,因此该异常向他的调用者方法meth()抛出,在main中Udine异常进行捕获
 */
class stt{
    private String studentNo,name;
    void setStudent(String stno,String nm) throws numException{
        if(stno.length()!=9)
            throw new numException("学号位数不对,应该是9位数。");
        studentNo=stno;
        name=nm;
    }
    void showInfo(){
        System.out.println("学号:"+studentNo);
        System.out.println("姓名:"+name);
    }
}
public class Exceptions2{
    public static void main(String[] args){
        stt st=new stt();
        try{
            st.setStudent("4324","张三");
        }catch(numException e){
            System.out.println(e.getReason());
        }
        st.showInfo();
    }
}
class numException extends Exception{
    private String reason;
    public numException(String r){
        reason=r;
    }
    public String getReason(){
        return(reason);
    }
}
/*
学号位数不对,应该是9位数。
学号:null
姓名:null
*/
//在setStdudent头部加了throw numException()短语,说明本方法可能抛出异常。当在Main方法中
//爸setStudent放在try语句块中,并随后对其进行异常捕获处理。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值