Differences and relationships between try-catch, throw, and throws

Source: Internet
Author: User

Difference 1: Throw is an exception thrown by the statement; throws is an exception thrown by the method;

Throw Syntax: Throw <exception Object>

In the method declaration, add the throws clause to indicate that the method will throw an exception. If a method has an exception but you do not want to handle it, use throws after the method name. This exception will be thrown. Whoever calls this method will handle this exception, or continue to throw.

Throws Syntax: [<modifier>] <return value type> <Method Name> ([<parameter list>]) [Throws <exception class>]

Multiple exception classes can be declared and separated by commas.

Difference 2: Throw can be used together with try-catch-finally statements or with throws. However, throws can be used independently and then captured by the exception handling method.

Contact 1: Try... catch is used to catch and handle exceptions in try. Catch is used to catch exceptions. In other words, an operation may throw any exception. Throw
Directly throws an exception without handling the exception.

When calling a method that will throws exception (which can be implemented by throws when the method is defined), you need to put this method in try, and then use catch to crack this exception and handle it accordingly.

Throw new exception () is an exception that is cracked by other methods.

That is to say, try... catch is used to crack others' exceptions, while throw throws itself throw exceptions to let others crack.

Public void input () throws exception

{}

Public void outputexception ()

{

Try {

Input ();

}

Catch (exception E)

{

System. Out. println ("exception ");

}

}

To put it simply, if throws is used in a method, this method will throw an exception. When calling this method, you must put this call in try... catch Block to handle this exception.

There are two ways to handle exceptions.

1. Either declare an exception, that is, add throws exceptionname,... after the method name. the method itself only throws an exception and is caught by the function caller. If an exception occurs, the exception moves down the call stack and finds the matching method. If the method is not found at the bottom of the call stack, the program is terminated.

2. Capture exceptions. Use the try catch method to place the exception handling statement in the catch clause.

Contact 2: Use try {} to wrap the block that will think an exception will be thrown, use catch to catch the exception, and handle the exception in catch, if there is an exception in try, the program will jump to catch without interruption. These two are usually used in combination. If you do not want to throw a lot of exceptions due to program errors, you can try the program. Try and catch can only get the exceptions that are thrown when the program is running, and throw statements can cause clear exceptions. The program stops immediately after it reaches the throw statement, will not execute subsequent programs,

You may be aware of errors in the programming process, but you do not know what exceptions will be thrown, which is also a headache. The following is a summary of this part:

Arithmetic exception class: arithmeticexecption
Null Pointer exception class: nullpointerexception
Type forced conversion exception: classcastexception
Array negative subscript exception: negativearrayexception
Array subscript out of bounds exception: arrayindexoutofboundsexcEption
Security violation exception: secturityexception
File ended exception: eofexception
File not found exception: filenotfoundexception
An error occurred while converting the string to a number: numberformatexception
Database Operation exception: sqlexception
Input and Output exceptions: ioexception
Method not found exception: nosuchmethodexception

 

 

 

Java exception handling is implemented through five keywords: Try, catch, throw, throws, and finally. The following keywords are explained in JB's online help :?
? ?
? Throws: lists the exceptions A method cocould throw .?
? ?
? Throw: transfers control of the method to the exception handler .?
? ?
? Try: Opening exception-handling statement .?
? ?
? Catch: captures the exception .?
? ?
? Finally: runs its code before terminating the program .?
? Try statement?
? The try statement specifies a piece of code with braces {}, which may discard one or more exceptions. ?
? ?
? Catch statement?
? The parameters of a catch statement are similar to the declaration of a method, including an exception type and an exception object. The exception type must be a subclass of the throwable class, which specifies the exception type processed by the catch statement. The exception object is born and captured by the runtime system in the code block specified by try, the braces contain the processing of objects, and the methods of objects can be called. ?
? ?
? There can be multiple catch statements to handle exceptions of different classes. During Java runtime, the system detects the exception types processed by each catch statement from top to bottom until a catch statement with the matching types is found. Here, type matching means that the exception type processed by catch is exactly the same as that of the natural exception object or its parent class. Therefore, the sort order of catch statements should be from special to general. ?
? ?
? ?
? ?
? You can also use a catch statement to process multiple exception types. In this case, its exception type parameter should be the parent class of these multiple exception types, in the program design, You must select the exception handling type of the catch statement according to the specific situation. ?
? ?
? Finally statement?
? In the Code defined by try, when an exception is discarded, the subsequent code will not be executed. You can use finally statements to specify a piece of code. No matter whether the exception type of the catch statement is the same as that of the discarded exception type in the block specified by try, the Code specified by finally must be executed, it provides the same egress. You can usually clear resources in finally statements. Such as closed open files. ?
? ?
? Throws statement?
? Throws always appear in a function header to indicate various exceptions that a member function may throw. For most exception subclasses, the Java compiler forces you to declare the types of exceptions thrown in a member function. If the exception type is error, runtimeexception, or their subclass, this rule does not work because it is not expected to appear in the normal part of the program. If you want to explicitly throw a runtimeexception, you must use the throws statement to declare its type. ?
? ?
? Throw statement?
? Throw always appears in the function body to throw an exception. The program will terminate immediately after the throw statement, the statement after it cannot be executed, and then in all try blocks containing it (possibly in upper-layer function calls) search for try blocks containing matched catch clauses from the inside out.

Class myexception extends exception {
? String MSG;
? Myexception (INT age ){
? MSG = "age can not be positive! ";
? }
? Public String tostring (){
? Return MSG;
? }?
}

Class age {
? Public void intage (int n) throws myexception {//
? If (n <0 | n> 120 ){
? Myexception E = new myexception (N );
? Throw E; // a turning statement that throws an object instance and stops executing the code
? }
? If (n> = 0 ){
? System. Out. Print ("fair age! ");
? }
? }
? ?
Public static void main (string ARGs []) {
? Int A =-5;
? Try {// try catch must have
? Age age = New Age ();
? Age. intage (a); // triggers an exception
? System. Out. Print ("code after an exception is thrown"); // this code will not be executed, and the program has been switched
? } Catch (myexception ex ){
? System. Out. Print (ex. tostring ());
? }
? Finally {// no matter whether an exception is thrown, no matter whether the exception type of the catch statement is the same as the type of the exception thrown, the Code specified by finally will be executed, it provides the same egress.
? System. Out. Print ("into finally! ");
? }
? }
}

Result: The age is invalid! Into finally !?

Another example:
Void fun () throws ioexception, sqlexception?
{?
...?
}?
This means that the fun method may lose two exceptions, so we will make preparations when calling fun. For example, can this happen?
Try?
{?
Fun ();?
} Catch (ioexception e )?
{?
} Catch (sqlexception e )?
{?

}

?

?

Difference 1:

? Throw is an exception thrown by the statement; throws is an exception thrown by the method;

? Throw Syntax: Throw <exception Object>

? In the method declaration, add the throws clause to indicate that the method will throw an exception.

? Throws Syntax: [<modifier>] <return value type> <Method Name> ([<parameter list>]) [Throws <exception class>]

? Multiple exception classes can be declared and separated by commas.

Difference 2:

? Throws can be used independently, but throws cannot;

Difference 3:

? Throw can be used together with try-catch-finally statements or with throws. However, throws can be used independently and then captured by the exception handling method.

?

Throws E1, E2, E3 only tell the program that this method may throw these exceptions, and the method caller may have to handle these exceptions. The E1, E2, and E3 exceptions may be generated by the function body.

Throw makes it clear that this exception should be thrown.

Void DOA () throws exception1, exception3 {
? Try {
? ......
? } Catch (exception1 e ){
? Throw E;
? } Catch (exception2 e ){
? System. Out. println ("error ");
? }
? If (! = B)
? Throw new exception3 ("custom exception ");
}

Code block ...... Exception exception1, exception2, and exception3.
If an exception1 exception is generated, the system captures the exception and then throws the caller of the method for processing;
If an exception2 exception is generated, the method is processed by itself (an error is printed), so the method will not throw the exception2 exception, void DOA () throws exception1, and prediction2 in excpetion3 do not need to be written;
The exception3 exception is a logical error in the method. If the programmer throws an exception exception3 when the logic error occurs, the caller also needs to handle it.

The throw statement is used in the method body to throw an exception. Is it handled by the statements in the method body?
The throws statement is used after the method declaration to throw an exception. It is handled by the statements in the upper-level method that calls this method.

Throws mainly declares that this method will throw this type of exception, so that the exception will be caught when it is called elsewhere.
Throw is a specific action to throw an exception, so it throws an exception instance.

Throws indicate your potential and preference?
If throw is used, you will turn that tendency into real.
At the same time:
1) throws appears in the method function header, while throw appears in the function body ;?
2) throws indicates the possibility of exceptions. Throw throws throw exceptions and throws exceptions ;?
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 handling is handled by the upper-layer call of the function.

 

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.