Use throw to throw an exception

Use throw to throw an 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 try blocks that contain it (possibly in the upper-level calling function), it will look from the inside out to the try block with the matching catch clause.

We know that an exception is an instance object of the exception class, and we can create an instance object of the exception class and throw it through the throw statement. The syntax of this statement is:

throw new exceptionname;

For example, an exception object of class IOException is thrown:

throw new IOException;

It should be noted that what throw can only throw is an instance object of the throwable class Throwable or its subclasses. The following operations are incorrect:

throw new String(“exception”);

This is because String is not a subclass of the Throwable class.

If a checked exception is thrown, the type of exception the method may throw should also be declared in the method header. The caller of this method must also check to handle the thrown exception.

If all methods throw the acquired exception layer by layer, the JVM will process it eventually, and the processing is also very simple, that is, printing the exception message and stack information. If an Error or RuntimeException is thrown, the caller of this method can choose 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("Divisor cannot be negative"); // Exception information
    }
    return x/y; // return value
  }
  public static void main(String args[]) { // main method
    int a =3;
    int b =0;  
    try { // try statement contains statements where exceptions may occur
      int result = quotient(a, b); // call method quotient()
    } catch (MyException e) { // handle custom exception
      System.out.println(e.getMessage()); // output exception message
    } catch (ArithmeticException e) { // handle ArithmeticException
      System.out.println("Divisor cannot be 0"); // Output prompt information
    } catch (Exception e) { // handle other exceptions
      System.out.println("other exceptions occurred in the program"); ​​// output prompt information
    }
  }
  
}
class MyException extends Exception { // Create custom exception class
  String message; // Define String type variable
  public MyException(String ErrorMessagr) { // parent class method
    message = ErrorMessagr;
  }
  
  public String getMessage() { // Override getMessage() method
    return message;
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325751909&siteId=291194637