Explain the use of the throw and throws keyword in Java exception handling

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

An exception is thrown
There are three forms of throwing an exception: a throw, a throw, and a system that throws an exception automatically. Here are the similarities and differences between them.
The system throws exceptions automatically
The system automatically throws an exception when a program statement has some logic errors, doctrinarity errors, or typecasting errors. Such as:


public static void main(String[] args) { 
    int a = 5, b =0; 
    System.out.println(5/b); 
    //function(); 
} 

The system automatically throws a ArithmeticException:


Exception in thread "main" java.lang.ArithmeticException: / by zero
at test.ExceptionTest.main(ExceptionTest.java:62)

  Again, such as


public static void main(String[] args) { 
    String s = "abc"; 
    System.out.println(Double.parseDouble(s)); 
    //function(); 
} 

The system will automatically throw a NumberFormatException:


Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1224)
at java.lang.Double.parseDouble(Double.java:510)
at test.ExceptionTest.main(ExceptionTest.java:62)

throw
Throw is a statement that throws an exception.
Syntax: throw (exception object);
          Such as:  


throw e;

This is typically used when a certain type of logic occurs in a program and the programmer actively throws a particular type of exception. Such as:


public static void main(String[] args) { 
    String s = "abc"; 
    if(s.equals("abc")) { 
      throw new NumberFormatException(); 
    } else { 
      System.out.println(s); 
    } 
    //function(); 
} 

Throws an exception:


Exception in thread "main" java.lang.NumberFormatException
at test.ExceptionTest.main(ExceptionTest.java:67)


throws
Throws is a declaration that a method may throw an exception. (used when declaring a method to indicate that the method might throw an exception)
Grammar: [(modifier)] (return value type) (way) ([parameter list]) [throws (exception class)] {... }
          Such as:          


 public void function() throws Exception{......}

Used to declare a possible exception when a method might throw it, and then to the method program that calls it at the top level. Such as:


public static void function() throws NumberFormatException{ 
    String s = "abc"; 
    System.out.println(Double.parseDouble(s)); 
  } 
   
  public static void main(String[] args) { 
    try { 
      function(); 
    } catch (NumberFormatException e) { 
      System.err.println(" Non-data types cannot be converted. "); 
      //e.printStackTrace(); 
    } 
} 

The results are as follows:
Non-data types cannot be converted.
Throw versus throw
1. Throws appears on the head of a method function; And throw appears in the body of the function.
2. Throws represents the possibility of exceptions that do not necessarily occur; A throw throws an exception, and an execution throw must throw some exception object.
3. Both are negative ways of handling exceptions (the negative here does not mean that this way is bad), just throw or may throw an exception, but not by the function to handle the exception, the real handling of the exception by the function of the upper call to handle.

Good programming habits:
1. When writing a program, try{... } catch {... } to capture it and process it;
2. Use the try {... } catch {... } after catching the exception, be sure to check the catch{... }, even the simplest output statement, or stack input e.php stacktrace ();
3. If you are catching an exception in the IO input/output stream, be sure to try{... } catch {... Finally add after} {... Close the input/output stream;
4. If an exception is thrown by a throw in the body of a function, it is a good idea to throw an exception declaration on the name of the function and pass it to the calling function.


For example:

Throws E1,E2,E3 simply tells the program that the method might throw these exceptions, that the caller of the method might handle these exceptions, and that E1,E2,E3 might be generated by the body of the function.
Throw specifies that this place is going to throw this exception.

Such as:


void doA(int a) throws IOException,{
      try{
         ......

      }catch(Exception1 e){
       throw e;
      }catch(Exception2 e){
       System.out.println(" Make a mistake! ");
      }
      if(a!=b)
       throw new Exception3(" Custom exception ");
}

Block of code may produce three exceptions, (Exception1 Exception2, Exception3).
If an Exception1 exception is generated, it is caught and thrown by the caller of the method.
If an Exception2 exception is produced, the method handles it itself (that is, system.out.println (" error!" ); . So this method will no longer throw Exception2 exception, void doA() throws exceptiontion1, Exception2 in Exception3.
An Exception3 exception is an error in a piece of logic of the method that the programmer handled himself to throw the exception Exception3 in the case of a logic error in that piece, and the caller of the method also handles the exception.

The throw statement is used in the method body to indicate that an exception is thrown and is handled by the statement in the method body.
The throws statement is used after a method declaration to indicate that another exception is thrown and is handled by the caller of that method.

A throws basically declares that the method throws this type of exception, letting its caller know to catch it.
Throw is the specific action of throwing an exception, so it is throwing an exception instance.

Throws indicates that you have a possibility or inclination.
Throw, you've made that tendency real.

If it is a system exception, you can do nothing, or you can throw an exception against a method, because the system exception can be automatically caught by the system, so whether the exception should be solved inside the method or handed to the upper function to solve the effect is the same. But I've done a lot of research, and I recommend writing a throw on a method even if it throws an exception that the system can catch, because it lets other programmers know what's going on when completing a large task.

If the exception is one of your own, you must throw the exception that the method might throw, otherwise the compilation will report an error.


Related articles: