Detailed Java exception handling throw and throws keyword usage difference _java

Source: Internet
Author: User
Tags throw exception

Throw an exception
there are three forms of throwing exceptions, one is throw, one throws, and the other is a system that automatically throws exceptions. Here are the similarities and differences between them.
System Auto Throw exception
An exception is thrown automatically when a program statement has a logical error, a doctrine error, or a type conversion error. Such as:

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

The system will automatically throw ArithmeticException exceptions:

Exception in thread ' main ' java.lang.ArithmeticException:/by zero at
test. Exceptiontest.main (exceptiontest.java:62)

Again as

public static void Main (string[] args) { 
    String s = "abc"; 
    System.out.println (double.parsedouble (s)); 
    function (); 
} 

The system will automatically throw NumberFormatException exceptions:

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;

Typically used when a program has some kind of logic, 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 might throw an exception. (When declaring a method, it indicates that the method may want to throw an exception)
Syntax: [(modifier)] (return value type) (method name) ([parameter list]) [Throws (Exception Class)]{...}
Such as:

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

When a method may throw an exception, it is used to throws the exception that the declaration might throw, and then to the upper level to call it the method handler. 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 type cannot be converted.") "); 
      E.printstacktrace (); 
    } 
 

The processing results are as follows:
Non-data types cannot be converted.
comparison of throw and throws
1, throws appears in the method function head, and throw appears in the function body.
2. Throws represents a possibility of an exception, which does not necessarily occur; throw throws an exception, and execution throw must throw some kind of exception object.
3, both are negative ways to deal with the exception (the negative here is not to say that this way is not good), just throw or may throw an exception, but not by the function to deal with the exception, the real handling of the exception by the function of the upper call processing.

Good programming Habits:
1. When writing a program, the part that is likely to have an exception is usually try{...} Catch{...} To capture it and deal with it;
2. Use try{...} Catch{...} After catching the exception, be sure to catch{...} To deal with it, that is even the simplest of the output statement, or stack input e.printstacktrace ();
3. If you are catching an exception in an IO input/output stream, be sure to try{...} Catch{...} After adding finally{...} Closing the input output stream;
4. If you throw an exception in a function body with throw, it is best to add throws to the function name and then to the upper function that calls it.


For Example:

Throws E1,e2,e3 simply tells the program that this method may throw these exceptions, and that the method's caller may want to handle the exceptions that may be generated by the function body.
Throw is clear about this place to throw this exception.

Such as:

void DoA (int a) throws ioexception,{
      try{...

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

3 exceptions may be generated in the code block (Exception1,exception2,exception3).
If a Exception1 exception is generated, it is caught and then thrown, which is handled by the caller of the method.
If a Exception2 exception is generated, the method handles itself (that is, the SYSTEM.OUT.PRINTLN ("Error!"). ");)。 Therefore, the method will not throw out the Exception2 exception, void DoA () throws Exception1,exception3 inside the Exception2 also do not have to write.
The Exception3 exception is a logical error in the method, which the programmer handles and throws an exception Exception3 in the case of a logical error, and the caller of the method handles the exception.

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

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

Throws shows that you have that possibility, inclination.
Throw, that's the way you turn that tendency into reality.

If the system is abnormal, you can do nothing, you can also throw an exception to the method, because the system exception can be automatically captured by the system, so this exception is to be resolved within the method or to the upper function to solve the effect is the same. But I've looked at a lot of data, even if it throws an exception to be captured by the system, it's recommended to write a throws for the method, because it allows other programmers to know what's going on here when a large task is done.

If you are defining an exception yourself, you must use throws to throw an exception that the method might throw, or the compilation will complain.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.