Java教程

Java throw异常


Java throw关键字用于显式抛出异常。
我们可以在Java中抛出选中或未选中的异常通过throw关键字。 throw关键字主要用于引发自定义异常。
下面将给出java throw关键字的语法。
throw exception;
让我们看看引发IOException的示例。
throw new IOException(sorry device error);

java throw关键字示例

在此示例中,我们创建了validate方法,该方法将整数值作为参数。如果年龄小于18岁,我们将抛出ArithmeticException,否则将显示一条消息,欢迎您投票。
public class TestThrow1{
    static void validate(int age){
        if(age<
        18) throw new ArithmeticException("not valid");
        else System.out.println("welcome to vote");
    }
    public static void main(String args[]){
        validate(13);
        System.out.println("rest of the code...");
    }
}
输出:
Exception in thread main java.lang.ArithmeticException:not valid
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4