Detailed explanation of Throw and Throws

Detailed explanation of Throw and Throws

What 1.throw that? What is the use?

Th throw is an operation about exceptions in java. If throw is used in try {} catch {}, it means that this method written by myself can handle the exception by itself, which is an action thrown, which can stop the program. And report the cause of the exception, basically realized that the program has detected its own exception and terminated the program. The advantage is that you can report the exception in the place you define to stop the program from running, instead of reporting the exception immediately in the wrong place and stopping Programs, so that the programs you write can detect errors yourself, without the last line of defense JVM to handle errors.

If not used, the error can only be handled by the JVM virtual machine when the error is reported (stop the program immediately at the error location and report the cause of the exception), indicating that the JVM virtual machine can only be used to detect and report the error.

What 2.throws that? What is the use?

The throws keyword is usually used when declaring a method to specify an exception that may be thrown. After the declaration, you can let the java compiler compile the class file normally for this java file. Once the class file is run, an error occurs during the period, the JVM virtual machine will detect the error, stop the program, and report the abnormal information.

And throws the difference 3.throw

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

Throws is mainly to declare that this method will throw this type of exception, so that its caller knows to catch this exception.
Throw is when a program has a certain logic error, the programmer actively throws a certain type of exception, specifically throwing an exception outward, so it is throwing an exception instance.

4. Comparison of throw and throws
1. Throws appear in the method function header; and throw appears in the function body.
2. Throws indicates a possibility of an exception, and these exceptions may not necessarily occur; throw is throwing an exception, and throwing must throw some kind of exception object.
3. Both of them are passive ways of handling exceptions (negative here is not to say that this way is not good), just throw or may throw exceptions, but the exception will not be handled by the function, the real exception handling is by the function Upper call processing.

5. The difference between throw e and e.printStackTrace ()

Th throw e is throwing an exception, will interrupt the program, the code behind is not executed.
E.printStackTrace () is to output the error log without interrupting the program.

Insert picture description here

Published 5 original articles · praised 4 · visits 15

Guess you like

Origin blog.csdn.net/qq_45218334/article/details/105618978