Java异常处理:Part3 自定义异常

来源:互联网 发布:附加遗产网络剧百度云 编辑:程序博客网 时间:2024/06/05 05:21
自定义异常Java不可能对所有的情况都考虑到,所以,在实际的开发中,我们可能需要自己定义异常。我们自己随意的写一个类,是不能作为异常类来看的。要想你的类是一个异常类,就必须继承自Exception或者RuntimeException 1.继承Exception 2.继承RuntimeException

1.MyException.java

package test_exception_custom;public class MyException extends Exception{}

2.MyException2.java

package test_exception_custom;public class MyException2 extends RuntimeException{    MyException2()    {    }       MyException2(String s)    {        super(s);    }}

3.Test1.java

package test_exception_custom;import java.util.Scanner;public class Test1 {    //测试继承自Exception的自定义异常MyException    public static int SCORE;    public static void check(int score)throws MyException    {        if(score<0||score>100)            throw new MyException();    }    public static void main(String[] args) {        // TODO Auto-generated method stub        System.out.print("请输入分数:");        Scanner sc=new Scanner(System.in);        SCORE=sc.nextInt();        sc.close();        try {            Test1.check(SCORE);//非运行时异常必须处理        } catch (MyException e) {            e.printStackTrace();        }        System.out.println(SCORE);    }}

结果为:
请输入分数:130
test_exception_custom.MyException
at test_exception_custom.Test1.check(Test1.java:11)
at test_exception_custom.Test1.main(Test1.java:20)
130

4.Test2.java

package test_exception_custom;import java.util.Scanner;public class Test2 {    //测试继承自RunTimeException的自定义异常MyException2        public static int SCORE;        public static void check(int score)        {            if(score<0||score>100)                throw new MyException2();        }    public static void main(String[] args) {        // TODO Auto-generated method stub         System.out.print("请输入分数:");            Scanner sc=new Scanner(System.in);            SCORE=sc.nextInt();            sc.close();            Test2.check(SCORE);//运行时异常不报错             System.out.println(SCORE);    }}

结果为:
请输入分数:130
Exception in thread “main” test_exception_custom.MyException2
at test_exception_custom.Test2.check(Test2.java:11)
at test_exception_custom.Test2.main(Test2.java:19)

5.Test3.java

package test_exception_custom;import java.util.Scanner;public class Test3 {    //测试继承自RunTimeException的自定义异常MyException2        public static int SCORE;        public static void check(int score)        {            if(score<0||score>100)                throw new MyException2("成绩应在0~100");        }    public static void main(String[] args) {        // TODO Auto-generated method stub         System.out.print("请输入分数:");            Scanner sc=new Scanner(System.in);            SCORE=sc.nextInt();            sc.close();            Test3.check(SCORE);//运行时异常不报错             System.out.println(SCORE);    }}

结果为:
请输入分数:130
Exception in thread “main” test_exception_custom.MyException2: 成绩应在0~100
at test_exception_custom.Test3.check(Test3.java:11)
at test_exception_custom.Test3.main(Test3.java:19)

0 0
原创粉丝点击