Throws and throw comparison, throwsthrow
1. The throws keyword is usually used to specify exceptions that may be thrown when the method is declared. Multiple exceptions can be separated by commas. When this method is called in the main function, if an exception occurs, the exception is thrown to the specified exception object. As shown in the following example:
Public class Shoot {create class
Static void pop () throws NegativeArraySizeException {
// Define the method and throw the NegativeArraySizeException
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
}
}
}
2. The throw keyword is usually used in the method body and an exception object is thrown. The program stops immediately when the throw statement is executed, and the subsequent statements are not executed. After throw an exception, if you want to capture and handle the exception in the code above, you need to use the throws keyword in the method that throws the exception to specify the exception to run in the method declaration; if you want to catch the exception thrown by throw, you must use the try-catch statement. Example:
Class MyException extends Exception {// create a custom Exception class
String message; // defines a String-type variable.
Public MyException (String ErrorMessagr) {// parent class Method
Message = ErrorMessagr;
}
Public String getMessage () {// overwrite the getMessage () method
Return message;
}
}
Public class Captor {// create a class
Static int quotient (int x, int y) throws MyException {// The definition method throws an exception.
If (y <0) {// determines whether the parameter is smaller than 0
Throw new MyException ("the divisor cannot be a negative number"); // exception information
}
Return x/y; // return Value
}
Public static void main (String args []) {// main method
Try {// try statement contains statements that may cause exceptions
Int result = quotient (3,-1); // call the quotient () method ()
} Catch (MyException e) {// handle custom exceptions
System. out. println (e. getMessage (); // output exception information
}
Catch (ArithmeticException e ){
// Handle ArithmeticException exceptions
System. out. println ("the divisor cannot be 0"); // output the prompt message.
}
Catch (Exception e) {// handle other exceptions
System. out. println ("Other exceptions occurred in the program ");
// Output prompt information
}
}
}