throw
Throw is used to throw objects of specific exception classes, generally used in method bodies.
When to use: throw an exception object to remind the programmer when the written code does not meet certain conditions and the program cannot run. Python like raise
public class Student { private int age; public int getAge() { return age; } public void setAge(int age) { if(age<150 && age>1) { this.age = age; }else { throw new AgeException("age The range is 1-150"); //Why not use the output statement here? //Because the output statement just outputs one sentence, it can't exactly locate the error position of the code like throwing an exception } } }
throws
throws is used to declare the exceptions that may be thrown by a method. It is followed by an exception class and can have multiple (comma "," interval). throws can only be used after the parentheses of the method declaration.
public class Test{ public static void show(int age) throws RuntimeException{//Use throws to keep throwing if(age<0 || age>150){ throw new RuntimeException("Age range is 0-150");//Here throw throws a runtime exception. If you don't use try catch, you need to use throws to continue throwing. If you are caught here, you don't need to continue throwing after the parameter list of this method } } public static void main(String[] args){ try{ new Test.show(1000); //Here we choose to use try catch statement, and here we can continue to throw. //If there is no operation here, the console will report an exception, and the program will not continue to execute until it is executed, that is, it will not output OK; after it continues to be thrown up, it will not execute the following code (multiple throws, the scope of the exception class to be thrown each time needs to be this class or its parent class) }catch(RuntimeException e){ e.printStackTrace(); } System.out.println("OK"); } }
- The throw keyword is usually used in the method body and throws an exception object. The program terminates immediately when it reaches the throw statement, and the subsequent statements do not execute. After throwing an exception through throw, if you want to catch and handle the exception in the upper level code, you need to use the throws keyword in the method throwing the exception to indicate the exception to be thrown in the method declaration; if you want to catch the exception thrown by throw, you must use the try catch statement block;
- If the code in the method or the code called in the method does not use throw to throw the exception class object, then you do not need to use throws, otherwise the exception class thrown by throws is invalid; that is, there must be code that uses throw to throw the exception object in the code in the throws method.
Custom exception
java has many built-in exceptions that may occur during programming. In addition, users can use a class to inherit Exception class to inherit custom class Exception.
To customize a class in a program, it is generally divided into the following steps:
- Create custom exception class
- Throw the exception object through the throw keyword in the method.
- If the exception is handled in the method that currently throws the exception, you can use the try catch statement block to catch and handle the exception. Otherwise, you can indicate the exception to be thrown to the method caller through throws in the method declaration, and continue with the next operation.
- A handle exception is caught in the caller of the method where the exception reappears.
Create a custom Exception. Create the class MyException in the project, which inherits the Exception.
public class MyException extends Exception{ //Create custom exception public MyException(String ErrorExceptin){ //Construction method super(ErrorExceptin); //Construction method of parent class } }
Create the TestException class in the project, and create a method Sum() with int type parameter in the class. If the method parameter is less than 0 or greater than 20, throw a MyException exception exception object through throw keyword, and catch the exception in main(). Here is the code example.
public class TestException { //Define method, throw exception private static int Sum(int num1,int num2)throws MyException{ if(num1<0||num2<0){ //Whether the parameters in the judgment method meet the conditions throw new MyException("Negative input parameter"); //error message } if(num1>20||num2>20){ //Whether the parameters in the judgment method meet the conditions throw new MyException("Input parameters greater than 20");//error message } return (num1+num2); //Output the sum of two numbers } public static void main(String []args){ try { //try code block handling possible exceptions int result=Sum(22,23); //Call Sum() method System.out.println(result); //Output the return value of Sum() method } catch (MyException e) { // TODO: handle exception System.out.println(e); //Output exception information } } }