码迷,mamicode.com
首页 > 编程语言 > 详细

java 异常处理3

时间:2019-07-11 09:30:35      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:class   cep   pre   异常处理   年龄   except   exception   strong   编译   

声明异常:
throws,不处理异常,丢给调用者处理

public static void f() throws IOException{
    ...
}
丢给调用方法处理
public static void main(String[]args) throws IOException{
    f();
}
main()方法丢给jre处理

自定义异常:
在运行时定义的异常用throw,如果是编译器异常则需要throws或try-catch,比如继承的是Exception

Person p=new Person();
        p.setAge(-1);

class Person{
    private int age;
    public void setAge(int age)
    {
        if(age<0)
        {
            throw new ill("年龄不能为负数");
        }
    }
    public int getAge()
    {
        return age;
    }
}

class ill extends RuntimeException{   //继承RuntimeException
    public ill()
    {

    }

    public ill(String s)
    {
        super(s); //使用父类的构造类方法
    }结果为:年龄不能为负数

java 异常处理3

标签:class   cep   pre   异常处理   年龄   except   exception   strong   编译   

原文地址:https://blog.51cto.com/14437184/2419087

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!