A further exploration of Java Foundation--throw and throws

Source: Internet
Author: User

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

A further exploration of Java Foundation--throw and throws

Although I know some unusual handling, but also used some, but the difference between throw and throws is not very clear. Test it with an example today.

Exception handling mechanism

Exception handling is the process of handling an exception that can occur to prevent the program from encountering an exception when it is stuck, in a waiting, or dead loop.

Exceptions have two procedures, one throws an exception, and one is a catch exception.

Throw exception

There are three forms of throwing exceptions, one is throw, one throws, and the other is an automatic system throw exception. The similarities and differences between them below.

Automatic System Throw exception

The system automatically throws an exception when a program statement has some logical error, a doctrine error, or a type conversion error. Such as:

[Java]View PlainCopy
    1. Public static void Main (string[] args) {
    2. int a = 5, b =0;
    3. System.out.println (5/b);
    4. //function ();
    5. }

The system will automatically throw ArithmeticException exceptions:

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

At Test. Exceptiontest.main (exceptiontest.java:62)

Again like

[Java]View PlainCopy
    1. Public static void Main (string[] args) {
    2. String s = "abc";
    3. System.out.println (double.parsedouble (s));
    4. //function ();
    5. }

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 certain type of exception. Such as:

[Java]View PlainCopy
  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. }

Will throw an exception:

Exception in thread "main" java.lang.NumberFormatException

At Test. Exceptiontest.main (exceptiontest.java:67)



Throws

Throws is a declaration in which the method may throw an exception. (used when declaring a method, indicating that the method might 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, the exception used for the throws declaration may be thrown, and then passed to the upper layer to invoke its handler. Such as:

[Java]View PlainCopy
  1. Public static void function () throws numberformatexception{
  2. String s = "abc";
  3. System.out.println (double.parsedouble (s));
  4. }
  5. public static void Main (string[] args) {
  6. try {
  7. function ();
  8. } catch (NumberFormatException e) {
  9. SYSTEM.ERR.PRINTLN ("Non-data type cannot be converted.  ");
  10. //e.printstacktrace ();
  11. }
  12. }

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 indicates that there is a possibility of an exception, which does not necessarily occur; throw throws an exception, and the throw throws a certain exception object.

3, both are negative handling of the abnormal way (the negative here is not to say this way bad), 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, you will usually use try{...} for parts that may appear to be abnormal. Catch{...} To capture it and deal with it;

2. With try{...} Catch{...} After catching the exception, be sure to catch{...} , even the simplest sentence of the output statement, or stack input e.printstacktrace ();

3. If you are capturing an exception in the IO input/output stream, be sure to try{...} Catch{...} After adding finally{...} The input/output stream is closed;

4. If an exception is thrown with a throw in the function body, it is best to add the throws throw exception declaration in the function name and then pass it on to the upper function that called it for processing.

Catching exceptions

First, catch exceptions.

[Java]View PlainCopy
    1. try{
    2. ......
    3. }catch (Exception e) {
    4. ......
    5. }finally{
    6. ......
    7. }

Try{...} A block of statements in which an exception can occur, such as a function that may occur with an exception, or a generic program statement; catch () {...} For catching exceptions, Exception is the type of exception in (Exception e) 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{...} Indicates that the processing in finally{} is performed regardless of whether the exception occurred.

try{to catch the exception ...} Statement block, if an exception occurs, the program statement after the statement (the statement with the exception) does not execute, but jumps to catch{...} The handling of exceptions is performed in the statement block. Such as:

[Java]View PlainCopy
  1. Public static void Function1 () throws numberformatexception{
  2. System.out.println (double.parsedouble ("abc"));
  3. System.out.println ("the second statement.  ");
  4. }
  5. public static void Main (string[] args) {
  6. try {
  7. Function1 ();
  8. } catch (Exception e) {
  9. System.err.println (E.getmessage ());
  10. //e.printstacktrace ();
  11. }
  12. }


As a result, only one error message is output:

For input string: "ABC"

System.out.println ("The second statement. "); not executed.

If a function does not throw an exception with throws, the method that invokes the function can also catch the exception. Such as

[Java]View PlainCopy
  1. Public static void function () {
  2. String s = "abc";
  3. System.out.println (double.parsedouble (s));
  4. }
  5. public static void Main (string[] args) {
  6. try {
  7. function ();
  8. } catch (Exception e) {
  9. SYSTEM.ERR.PRINTLN ("Non-data type cannot be converted.  ");
  10. //e.printstacktrace ();
  11. }
  12. }

The processing results are as follows:

Non-data types cannot be converted.

Description: a function or a block of blocks whether or not, there is no possibility of throwing an exception, you can add try{...} Catch{...} To catch it.

Custom exceptions

The user can customize the exception by creating a new exception class that inherits a subclass of the exception class or exception. The exception class object that you define is then thrown with throw. Such as:

[Java]View PlainCopy
  1. Public static void function () throws parenthesismatchingexception{
  2. String s = "((a+b)";
  3. Parenthesismatchingexception e = new Parenthesismatchingexception ("parentheses match the exception!")  ");
  4. if (S.charat (0) = =' (' && S.charat (1) = =' (') {
  5. throw E;
  6. }
  7. System.out.println (s);
  8. }
  9. public static void Main (string[] args) {
  10. try {
  11. function ();
  12. } catch (Exception e) {
  13. System.out.println (E.getmessage ());
  14. //e.printstacktrace ();
  15. }
  16. }


The results are as follows:

Parentheses match the exception!

A further exploration of Java Foundation--throw and throws

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.