The way to throw an exception is more direct:
if(age < 0){throw new MyException("Age cannot be negative!");} Let’s take a 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 operation results are as follows:
In Java, an exception can be declared when a method is defined, and then throwing an exception can be used to specifically throw during implementation.
ppublic class Shoot { Create class static void pop() throws NegativeArraySizeException { //Define the method and throw NegativeArraySizeException exception int [] arr = new int[-3];/ /Create an array} public static void main(String[] args) {//Main method try { pop(); //Call the pop() method} catch (NegativeArraySizeException e) { System.out.println("Exception thrown by the pop() method");//Output exception information}} }