A quick look at how exceptions are thrown in Java programming

  • 2020-04-01 04:24:21
  • OfStack

Any Java code can throw an exception, such as your own code, code from the Java development environment package, or the Java runtime system. Anyone can throw an exception through Java's throw statement. Any exception thrown from a method must use the throws clause.

1. Throws an exception

If a method might throw an exception but has no ability to handle it, you can declare a throw exception at the method declaration using the throws clause. For example, when the car is running, it may break down. The car itself cannot deal with the fault, so let the driver deal with it.

The throws statement is used at method definition to declare the type of Exception to be thrown by the method, and if the Exception Exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be separated by commas. The syntax format of the throws statement is:

Methodname throws Exception1 Exception2,.. ExceptionN 

}
Throws Exception1,Exception2,... ,ExceptionN is the list of exceptions declared to be thrown. When a method throws an exception to the list of exceptions, the method does not handle the exceptions of these types and their subtypes, but instead throws them to the method that calls the method. Such as:


import java.lang.Exception; 
public class TestException { 
  static void pop() throws NegativeArraySizeException { 
    //Define methods and throw NegativeArraySizeException anomalies
    int[] arr = new int[-3]; //Create an array
  } 
  
  public static void main(String[] args) { //The main method
    try { //The try statement handles exception information
      pop(); //Call the pop() method
    } catch (NegativeArraySizeException e) { 
      System.out.println("pop() The exception thrown by the method ");//Output abnormal information
    } 
  } 
  
}

After throwing the exception to the caller using the throws keyword, if the caller does not want to handle the exception, it can continue to throw it up, but eventually there must be a caller capable of handling the exception.

Instead of dealing with abnormal NegativeArraySizeException, pop method by the main function to deal with.

The rule on throwing an exception:

1) if it is an unchecked exception (Error, RuntimeException, or a subclass of them), you can declare the exception to be thrown without the throws keyword, and the compilation will still pass, but it will be thrown at run time.

2) you must declare any checked exceptions that the method can throw. That is, if a method is likely to have a passable exception, it is either caught with a try-catch statement or thrown with a throws clause declaration, which results in a compilation error

3) it is only when an exception is thrown that the caller of the method must handle or rethrow the exception. When the caller of a method is unable to handle the exception, it should continue to throw it, rather than swallowing it.

4) the method must follow any rules for handling and declaring exceptions that can be checked. If you override a method, you cannot declare an exception that is different from the override method. Any exception declared must be a class or subclass of the exception declared by the overridden method.

Such as:

The following is the basis for judging that an anomaly may occur in a method:

1) there is a throw statement in the method. For example, the catch block for the above method7() method has a throw statement.

2) another method is called, and the other method declares to throw an exception with the throws clause. For example, the method3() method calls the method1() method, and the method1() method declares that it throws an IOException, so an IOException may occur in the method3() method.

Throw an exception

Throw always appears in the body of the function to throw an exception of type Throwable. The program terminates immediately after the throw statement, the statement that follows it fails to execute, and then looks inside out of all the try blocks that contain it (possibly in the upper calling function) for the try block that contains the catch clause that matches it.

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 with a throw statement. The syntax of this statement is:


throw new exceptionname;

For example, an exception object that throws an IOException class:


throw new IOException;

Note that throw can only throw an instance object of the Throwable class Throwable or a subclass thereof. The following operation is wrong:


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 might throw in the method header. The caller of the method must also check the exception thrown by the handler.

If all the methods were to throw up the fetched exception layer by layer, eventually the JVM would do the processing, which is as simple as printing 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 methods that throw exceptions
    if (y < 0) { //Determine whether the parameter is less than 0
      throw new MyException(" The divisor cannot be negative "); //Exception information
    } 
    return x/y; //The return value
  } 
  public static void main(String args[]) { //The main method
    int a =3; 
    int b =0;  
    try { //The try statement contains statements where exceptions can occur
      int result = quotient(a, b); //Call method quotient()
    } catch (MyException e) { //Handles custom exceptions
      System.out.println(e.getMessage()); //Output abnormal information
    } catch (ArithmeticException e) { //Handle the ArithmeticException exception
      System.out.println(" The divisor cannot be zero 0"); //Output prompt message
    } catch (Exception e) { //Handling other exceptions
      System.out.println(" Other exceptions occurred to the program "); //Output prompt message
    } 
  } 
  
} 
class MyException extends Exception { //Create a custom exception class
  String message; //Define variables of type String
  public MyException(String ErrorMessagr) { //The parent class method
    message = ErrorMessagr; 
  } 
  
  public String getMessage() { //Override the getMessage() method
    return message; 
  } 
}


Related articles: