Home > Java > javaTutorial > body text

Detailed explanation of the difference in usage of throw and throws keywords in Java exception handling

高洛峰
Release: 2017-01-18 14:50:01
Original
2102 people have browsed it

Throwing exceptions
There are three forms of throwing exceptions, one is throw, the other is throws, and the system automatically throws exceptions. Below are the similarities and differences between them.
The system automatically throws exceptions
When there are some logical errors, doctrinal errors or type conversion errors in program statements, the system will automatically throw exceptions. For example:

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

The system will automatically throw ArithmeticException:

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

Another example is

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

The system will automatically throw a NumberFormatException exception:

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)
Copy after login

throw
throw is an exception thrown by the statement.
Syntax: throw (exception object);
Such as:

throw e;
Copy after login

Generally used when the program has certain logic, the programmer actively throws a specific type of exception. . For example:

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

will throw an exception:

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

throws
throws is a statement that the method may throw an exception. (Used when declaring a method, it indicates that the method may throw an exception)
Syntax: [(modifier)](return value type)(method name)([parameter list])[throws(exception class)]{ ......}
For example:

public void function() throws Exception{......}
Copy after login

When a method may throw some kind of exception, it is used in throws to declare the exception that may be thrown, and then hand it to The upper layer calls its method program for processing. For example:

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("非数据类型不能转换。");
      //e.printStackTrace();
    }
}
Copy after login

The processing result is as follows:
Non-data types cannot be converted.
Comparison between throw and throws
1. Throws appears in the method function header; and throw appears in the function body.
2. Throws represents a possibility of exceptions, but these exceptions may not necessarily occur; throw means an exception is thrown, and some kind of exception object must be thrown when executing throw.
3. Both are passive ways of handling exceptions (the negative here does not mean that this way is bad). They only throw or may throw exceptions, but the exceptions will not be handled by the function, and the exceptions will actually be handled. Handled by the upper layer call of the function.

Good programming habits:
1. When writing a program, you usually use try{...}catch{...} to catch the part where an exception may occur and execute it. Processing;
2. After catching the exception with try{...}catch{...}, you must process it in catch{...}, even if it is the simplest output statement, Or stack input e.printStackTrace();
3. If you are catching exceptions in the IO input and output stream, be sure to add finally{...} after try{...}catch{...} to put the input The output stream is closed;
4. If a certain exception is thrown using throw in the function body, it is best to add a throws exception statement to the function name, and then hand it over to the upper-level function that calls it for processing.


Example:

throws E1, E2, E3 just tell the program that this method may throw these exceptions, and the caller of the method may have to handle these exceptions, and these exceptions E1, E2 and E3 may be generated by the function body.
throw makes it clear that this exception is to be thrown in this place.

For example:

void doA(int a) throws IOException,{
      try{
         ......
 
      }catch(Exception1 e){
       throw e;
      }catch(Exception2 e){
       System.out.println("出错了!");
      }
      if(a!=b)
       throw new Exception3("自定义异常");
}
Copy after login

Three exceptions may occur in the code block, (Exception1,Exception2,Exception3).
If an Exception1 exception occurs, it will be thrown after being caught and handled by the caller of the method.
If an Exception2 exception occurs, the method handles it by itself (i.e. System.out.println("An error occurred!");). Therefore, this method will no longer throw Exception2 exceptions, and void doA() throws Exception1, Exception2 in Exception3 does not need to be written.
The Exception3 exception is a certain logic error in the method. The programmer has handled it himself. If the exception Exception3 is thrown in the case of a logic error, the caller of the method must also handle this exception.

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

throws mainly declares that this method will throw this type of exception so that its caller knows to catch this exception.
throw is a specific action of throwing an exception, so it throws an exception instance.

throws shows that you have that possibility and tendency.
throw, then you have turned that tendency into reality.

If it is a system exception, you don’t need to do anything, or you can throw an exception for the method, because system exceptions can be automatically caught by the system, so whether this exception should be resolved inside the method or handed over to The upper-layer function actually has the same effect. But I checked a lot of information, and even if an exception is thrown and can be caught by the system, it is still recommended to write a throws for the method, because this can let other programmers know what exceptions will occur when completing a large task.

If it is a self-defined exception, you must use throws to throw the exception that may be thrown by the method, otherwise the compilation will report an error.

For more detailed explanations on the usage differences between throw and throws keywords in Java exception handling, please pay attention to the PHP Chinese website for related articles!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template