Java异常的知识讲解

x33g5p2x  于2021-11-22 转载在 Java  
字(1.4k)|赞(0)|评价(0)|浏览(336)

创建一个 Java 数组,然后访问不存在的数组数据,看看会抛出什么异常:

我们可以看到抛出了一个ArrayIndexOutOfBoundsException:异常:数组下标越界

执行代码 System.out.println(1 / 0),看看会抛出什么异常。

现在抛出了一个ArithmeticException: / by zero异常

Thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.
当出现异常的运算条件时,抛出此异常。
例如,一个整数“除以零”时,抛出此类的一个实例。

自定义异常:

package 任务5;

/** * @author ${范涛之} * @Description * @create 2021-11-18 0:10 */
public class MyExpection {

    public static void main(String[] args) throws GenderException {
        Human human = new Human();
        human.setGender("牛");


    }

    public static class Human{
        static String gender;

        public static void setGender(String s) throws GenderException{ //这里抛出了自己的异常

            GenderException g= new  GenderException();

            if (!s.equals("男") && !s.equals("女")){

// throw new GenderException("");

// throw new GenderException("你输入了错误的性别");

// throw new GenderException(g,"你输入了错误的性别");

                throw new GenderException("你输入了错误的性别");

            }
            else {
                gender = s;

            }

        }

    }




    public static class GenderException extends Exception{

        /** * 构造方法1:无异常 */
        public GenderException(){
            super();
        }

        /** * 构造方法二:有字符串异常 * @param message */
        public GenderException(String message){
            super(message);
        }

        /** * 构造方法三:有字符串和Throwable类型参数,表明异常可以抛出 * @param message * @param cause */
        public GenderException(Throwable cause,String message){
            super(message,cause);
        }

        /** * 构造方法四:有Throwable类型参数,表明异常可以抛出 * @param cause */
        public GenderException(Throwable cause){
            super(cause);
        }




    }



}

不同的输出结果:

相关文章