Exception mechanism and difference between throw and throws

Source: Internet
Author: User
Tags try catch

Java Exception Handling

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 generated 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 the type of the generated 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 a uniform exit. You can usually clear resources in finally statements. For example, close 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 ("reasonable age! ");
}
}

Public static void main (string ARGs []) {
Int A =-5;
Try {// try catch is required
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 a uniform exit.
System. Out. Print ("enter finally! ");
}
}
}

Result: The age is invalid! Go to finally!

Another example:
Void fun () throws ioexception, sqlexception
{
...
}
This means that two exceptions may be thrown out of the fun method, so you will be prepared when calling fun, for example, you can
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 occurs after printing), 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 and is processed 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 a possibility of exceptions, which may not always occur. Throw throws exceptions and throws certain exceptions;
3) both are passive Exception Handling Methods (here the negative is not to say that this method is not good). It only throws or may throw an exception, but it is not 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.