Java basics-throw, throws, and javathrowthrows

Source: Internet
Author: User

Java basics-throw, throws, and javathrowthrows

Reprinted: http://blog.csdn.net/luoweifu/article/details/10721543

Explore the Java basics-throw and throws

In the past, although some exceptions were handled and used, the difference between throw and throws is still unclear. Test it with an instance today

Exception Handling Mechanism

Exception Handling is to process possible exceptions to prevent the program from getting stuck, waiting, or endless loops.

Two processes are involved: one is to throw an exception and the other is to catch an exception.

Throw an exception

Throws can be thrown in three forms: throw, throws, and automatic throws. The similarities and differences between them below

The system automatically throws an exception

The system automatically throws an exception when a program statement encounters a logical, procedural, or type conversion error. For example:

1 public static void main(String[] args) {  2         int a = 5, b =0;  3         System.out.println(5/b);  4         //function();  5 } 
The system automatically throws the ArithmeticException:

Exception in thread "main" java. lang. ArithmeticException:/by zero

At test. ExceptionTest. main (ExceptionTest. java: 62)

Another example is:
1 public static void main(String[] args) {  2         String s = "abc";  3         System.out.println(Double.parseDouble(s));  4         //function();  5 }  
The system automatically throws 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 an exception thrown by a statement.

Syntax: throw (exception object );

For example, throw e;

Generally, it is used when a program encounters a certain logic, and the programmer throws a certain type of exception. For example:

1 public static void main(String[] args) {  2         String s = "abc";  3         if(s.equals("abc")) {  4             throw new NumberFormatException();  5         } else {  6             System.out.println(s);  7         }  8         //function();  9 }

An exception is thrown:

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. (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 {......}

When a method may throw an exception, it is used to declare the exception that may be thrown by throws and then handed over to the upper-layer method program for processing. For example:

1 public static void function () throws NumberFormatException {2 String s = "abc"; 3 System. out. println (Double. parseDouble (s); 4} 5 6 public static void main (String [] args) {7 try {8 function (); 9} catch (NumberFormatException e) {10 System. err. println ("non-data type cannot be converted. "); 11 // e. printStackTrace (); 12} 13}

The processing result is as follows:

Non-data types cannot be converted.

  • Comparison between throws and throws

1. throws appears in the method function header, while throw appears in the function body.

2. throws indicates a possibility of exceptions, which may not always occur. throw throws throw an exception, and throw an exception object.

3. Both of them are passive Exception Handling Methods (here the negative is not to say that this method is not good). They only throw or may throw an exception, but will not be handled by the function, the real exception is handled by the upper-layer call of the function.

  • Good Programming habits:

1. When writing a program, try {...} catch {...} to catch the exception and process it.

2. use try {...} catch {...} after an exception is caught, make sure that the catch {...} to process it, I am afraid it is the simplest output statement or stack input e. printStackTrace ()

3. If an exception is caught in the IO input/output stream, add finally {...} After try {...} catch {...} to close the input/output stream.

4. If throw throws an exception in the function body, it is best to add throws to the function name to throw the exception declaration and hand it over to the upper-layer function that calls it for processing.

  • Capture exceptions

Capture exceptions first

1 try{  2  ……  3 }catch(Exception e){  4  ……  5 }finally{  6  ……  7 } 

Try {......} Block where exceptions may occur, such as abnormal functions, can also be general program statements; catch (){......} Used to catch exceptions. In (Exception e), Exception is the Exception type and must be a subclass of Exception (Exception is the parent class of all Exception classes. {} Defines the processing method when an exception occurs. Finally {......} Whether or not an exception occurs, it must be processed in finally {}.

In the catch exception try {...} in the statement block, if an exception occurs, the program statements after this statement (an exception occurs) are not executed, but jump to catch {...} statement block. For example:

1 public static void function1 () throws NumberFormatException {2 System. out. println (Double. parseDouble ("abc"); 3 System. out. println ("second statement. "); 4 5} 6 7 public static void main (String [] args) {8 try {9 function1 (); 10} catch (Exception e) {11 System. err. println (e. getMessage (); 12 // e. printStackTrace (); 13} 14}

Only one error prompt is output as follows:

For input string: "abc"

System. out. println ("second statement. "); Not executed.

If a function does not throws an exception, the method that calls the function can also catch the exception. For example:

1 public static void function () {2 String s = "abc"; 3 System. out. println (Double. parseDouble (s); 4} 5 6 public static void main (String [] args) {7 try {8 function (); 9} catch (Exception e) {10 System. err. println ("non-data type cannot be converted. "); 11 // e. printStackTrace (); 12} 13}

The processing result is as follows:

Non-data types cannot be converted.

Note:Whether or not a function or a block can throw an exception, you can add try {...} catch {...} to catch it.

  • Custom exception

You can create an Exception class to inherit the Exception class or a subclass of Exception. Then throw the custom exception class object with throw.

During program development, the following four steps are taken for custom exceptions:

  1) first create a custom Exception class. Syntax format: custom Exception class name extends Exception.

 

2) throw an exception object through the keyword throw in the method.

 

3) if an exception is handled in the method currently thrown, use the try-catch statement to capture and handle the exception. If not, use the keyword throws in the method declaration to specify the exception to be thrown to the method call.

4) capture and handle exceptions in calling methods with exceptions

For example:

1 public static void function () throws ParenthesisMatchingException {2 String s = "(a + B)"; 3 ParenthesisMatchingException e = new ParenthesisMatchingException ("Bracket matching exception! "); 4 if (s. charAt (0) = '(' & s. charAt (1) = '(') {5 throw e; 6} 7 System. out. println (s); 8} 9 10 public static void main (String [] args) {11 try {12 function (); 13} catch (Exception e) {14 System. out. println (e. getMessage (); 15 // e. printStackTrace (); 16} 17}
The result is as follows:

An error occurred while matching the brackets!

Related Article

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.