throw throws an exception in a more direct way:
if(age < 0){ throw new MyException("年龄不能为负数!"); }
Let’s look at an example:
package Test; public class Test2 { public static void main(String[] args) { String s = "abc"; if(s.equals("abc")) { throw new NumberFormatException(); } else { System.out.println(s); } } }
The running results are as follows:
In Java, you can declare an exception when a method is defined, and then you can use throw to specifically throw an exception during implementation.
ppublic class Shoot { 创建类 static void pop() throws NegativeArraySizeException { //定义方法并抛出NegativeArraySizeException异常 int [] arr = new int[-3];//创建数组 } public static void main(String[] args) {//主方法 try { pop(); //调用pop()方法 } catch (NegativeArraySizeException e) { System.out.println("pop()方法抛出的异常");//输出异常信息 } } }
For more related articles about using the throw keyword to throw exceptions in Java programming, please pay attention to the PHP Chinese website!