Any Java code can throw exceptions, such as: code written by yourself, code from the Java development environment package, or Java runtime system. No matter who it is, you can throw an exception through the Java throw statement. Any exception thrown from the method must be used with the throws clause.
1. throws throw exception
If a method may have an exception but does not have the ability to handle such an exception, you can use the throws clause to declare the thrown exception at the method declaration. For example, a car may fail when running, and the car itself cannot handle this failure, so let the driver deal with it.
The throws statement is used to declare the type of exception to throw when the method is defined. If the Exception exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be split using commas. The syntax format of the throws statement is:
methodname throws Exception1,Exception2,..,ExceptionN
{
}
throws after the method name Exception1,Exception2,…,ExceptionN is the list of exceptions to be thrown. When a method throws an exception list of exceptions, the method will not handle exceptions of these types and their subclass types, but will be thrown to the method that calls the method and will be handled by it. For example:
import java.lang.Exception; public class TestException { static void pop() throws NegativeArraySizeException { // Define the method and throw NegativeArraySizeException onException int[] arr = new int[-3]; // Create an array} public static void main( String[] args) { // Main method try { // try statement handles exception information pop(); // Call the pop() method} catch (NegativeArraySizeException e) { System.out.println("pop() method thrown exception");// Output exception information} } }
After throwing the exception to the caller using the throws keyword, if the caller does not want to handle the exception, you can continue to throw it up, but in the end there must be a caller who can handle the exception.
The pop method does not handle the exception NegativeArraySizeException, but is handled by the main function.
The rule for Throws to throw exceptions:
1) If it is an unchecked exception, that is, Error, RuntimeException or their subclasses, you can declare the exception to be thrown without using the throws keyword, and the compilation will still pass smoothly, but it will be run by the system during runtime. Throw out.
2) Any checked exceptions that can be thrown by the method must be declared. That is, if a method may have a checkable exception, it will either be caught with a try-catch statement or declared with a throws clause, otherwise it will cause a compile error.
3) Only when an exception is thrown, the caller of the method must handle or re-throw the exception. When the method caller is unable to handle the exception, it should continue to throw it instead of swallowing it whole.
4) The calling method must follow any checkable exception handling and declaration rules. If a method is overwritten, exceptions that are different from the overwritten method cannot be declared. Any exception declared must be a similar or subclass of the exception declared by the overridden method.
For example:
The basis for determining that an exception may occur in a method is as follows:
1) There is a throw statement in the method. For example, the catch code block of the above method7() method has a throw statement.
2) Other methods are called, and other methods use throws clause to declare some exception to throw. For example, the method3() method calls the method1() method, and the method1() method declares that an IOException is thrown, so an IOException may occur in the method3() method.
2. Use throw to throw exception
throw always appears in the function body and is used to throw an exception of type Throwable. The program will terminate immediately after the throw statement, the statement after it cannot be executed, and then in all the try blocks containing it (perhaps in the upper-level calling function) look for try blocks containing the catch clause that matches it from the inside out.
We know that exceptions are instance objects of exception class, and we can create instance objects of exception class to be thrown through throw statement. The syntax format of this statement is:
throw new exceptionname;
For example, throw an exception object of the IOException class:
throw new IOException;
It should be noted that throws only instance objects that can throw class Throwable or subclasses. The following operation is incorrect:
throw new String("exception");
This is because String is not a subclass of the Throwable class.
If a check exception is thrown, you should also declare the type of exception that the method may throw in the method header. The caller of this method must also check for handling the thrown exception.
If all methods throw the acquired exception layer by layer, the JVM will eventually process it, and the processing is also very simple, which is to print the exception message and stack information. If an Error or RuntimeException is thrown, the caller of the method has the option to handle the exception.
package Test; import java.lang.Exception; public class TestException { static int quotient(int x, int y) throws MyException { // Define method to throw exception if (y < 0) { // Determine whether the parameter is less 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 int a =3; int b =0; try { // The try statement contains statements that may have exceptions int result = quotient(a, b); // Call the method quotient() } catch (MyException e) { // Handle custom exception System.out.println(e. getMessage()); // Output exception information} catch (ArithmeticException e) { // Handle ArithmeticException exception System.out.println("The divisor cannot be 0"); // Output prompt information} catch (Excepti on e) { // Handle other exceptions System.out.println("Other exception occurred in the program"); // Output prompt message} } } class MyException extends Exception { // Create a custom exception class String message; // Define String type variable public My Exception (String ErrorMessagr) { // Parent class method message = ErrorMessagr; } public String getMessage() { // Override getMessage() method return message; } }