Big Data Java Foundation 14th Day

Source: Internet
Author: User
Tags finally block terminates

1.Java Exception

In the process of using computer language for project development, even if the programmer writes the code perfectly, there are still some problems in the running of the system, because many problems can not be avoided by the code, such as: the format of the customer input data, the range of input values, the existence of the read file, Whether the network remains unobstructed and so On.

As far as possible, the program designer needs to anticipate all possible situations and ensure that the program can run in all the worst cases possible.

But in fact, there are numerous unexpected cases, and the program may be unusually far more than the programmer can take into account in the unexpected Situation.

Java exception handling mechanism can make the program have good fault tolerance, make the program more robust, when the program is abnormal, the system will automatically generate a exception object to notify the program, so that the "business function implementation code" and "error handling code" separation, so that the program has better Readability.

2. Abnormal Exception

Exceptions refer to errors that occur at run time, syntax errors that occur during compilation, and so on, which cannot be called Exceptions.

The exception events that occur during the runtime of a Java program can be divided into two categories: error Exception, which does not contain syntax errors, and is an inheritance diagram for exception classes in Java:

    • Error

A serious problem that the Java Virtual machine cannot Resolve. Such as: JVM system internal errors, system crashes, dynamic link failures, and so on, This error cannot be recovered or is not possible to capture, will cause the application to break, usually the program cannot handle these errors, so the program does not attempt to use catch block to catch the error object. Generally not processed.

    • Exception

Other general problems caused by programming errors or accidental external factors can be handled using targeted Code. For example: arithmetic exception, null pointer access, array subscript out of bounds, the file to be read does not exist, etc.

L are divided into two main categories:

L A class is a compilation exception, must be processed before normal compilation (class cannot find, IO exception ...) In the API documentation explicitly stated throws ... Methods that must be processed)

L class is run-time exception runtimeexception, This exception can be handled, also can not handle (arithmetic exception, null pointer, etc.)

3. Run-time Exceptions

Refers to exceptions that the compiler does not require to be forced to dispose of. Usually refers to the programming logic error, is the programmer should actively avoid its occurrence of the Exception. The Java.lang.RuntimeException class and its subclasses are Run-time Exceptions.

For such exceptions, it can be done without processing because such exceptions are common, and if full processing can have an impact on the readability and operational efficiency of the Program.

4. Compiling Exceptions

Refers to an exception that the compiler requires to dispose Of.

Java programs must catch or declare all Compile-time exceptions.

For this kind of exception, if the program does not process, may bring unexpected results, compilation can not pass

5. Workaround for Run-time exceptions

For these run-time exceptions (not compile exceptions), There are generally two workarounds:

    • One is to terminate the operation of the program if it encounters an error, that is, the exception is not processed
    • The second is that the programmer, when writing the program, take into account the error detection, error message prompt, when thrown to the Java runtime environment, the exception object is captured, and then processed (printing prompt information, etc.)

Try Attempt: Place the statement where the exception might have occurred

Catch Capture: When an exception in a try block occurs, an exception object is generated that matches the exception class in the Catch block, and if the type in the catch is matched, the statement in the catch block is executed, which means that the catch block can have more than one.

As can be seen from the above program, a try can be added to a number of catch blocks, for the exception of the TRY statement block occurred in a separate capture, of course, only one catch block can be executed, from the logical view of execution, and the switch branch statement very similar.

If the exception catch block corresponding to the exception class is placed in front of it, the catch block will go straight in the event of an error, because all exceptions are instances of exception or its subclasses, and the catch block behind it will never be executed.

In fact, when you do an exception capture, you should not only put the catch block corresponding to the exception class at the end, but all the parent exception blocks should be placed after the subclass exception catch block, précis-writers: handle the small exception (child) first, and then handle the large exception (parent). otherwise, compilation Error

6. Access exception Information

If the program needs to access information about the exception object in the catch block, it can be obtained by accessing the exception parameter after the catch block, and when the Java runtime decides to call a catch block to process the exception object, the exception object is assigned to the exception argument after the catch block (that is, the parameter of the exception Type) , the program can use this parameter to obtain information about the Exception.

All of the exception objects contain the following common Methods:

    • GetMessage (): Returns the detailed description of the exception
    • Printstacktrace (): Print out the trace stack information for the exception
    • Printstacktrace (printstream s): outputs the Exception's trace stack information to the specified output stream
    • Getstacktrace (): Returns the trace stack information for this exception
7. Type Conversion exception:classcastexception

Import java.util.Date;

public class Errordemo {

public Static void main (string[] Args) {

Object obj = new Date ();

String str = (string) obj;

}

}

8. Null pointer exception: nullpointerexcetion

@Test

public void test5 () {

String str = New string ("AA");

str = null;

System.out.println (str.length ());

}

9. Compile-time Exceptions (must be captured)

When you view the method declaration in the API with the throws keyword

Import java.io.FileInputStream;

Import java.io.FileNotFoundException;

public class Errordemo {

public Static void main (string[] Args) {

FileInputStream in = null;

in = new fileinputstream ("a.txt");//error, no capture

Try {

in = new fileinputstream ("a.txt");//may throw an exception and must be captured

}catch(filenotfoundexception Fe) {

Fe.printstacktrace ();

}

}

}

10. Use finally to reclaim resources

sometimes, Some physical resources, such as database connections, network connections, disk files, and so on, are opened in a try statement block, and these physical resources must be explicitly reclaimed.

The garbage collection mechanism in Java does not reclaim any physical resources, and the garbage collection mechanism can only reclaim memory resources that are consumed by objects in memory.

So where do you recycle physical resources? Can you do that in a try statement block? If an exception is executed in a try block, the statement after the statement does not have a chance to execute, which results in subsequent resource collection statements not being Executed. If you perform a resource collection in a catch block, The catch statement block may not be executed at all, which can also cause the resource to not be Reclaimed.

To ensure that physical resources opened in a try block are recoverable, the exception handling mechanism provides a finally block, regardless of which statement in the try is thrown, and no matter which catch block is executed, or even executes a return statement in a try or Catch. Finally blocks are always Executed. The complete exception handling structure syntax is as Follows:

try{

Business Processing Statements

}catch (exception 1 E1) {

Exception Handling Statements

}catch (exception 2 E2) {

Exception Handling Statements

}

...

finally{

Resource Recycling Statements

}

11. Note:

In the exception-handling structure, only the try block is required, that is, if there is no try block, then no subsequent catch and finally block, catch and finally appear at least one, of course, can also appear The catch block that captures the subclass exception must be in front of the catch block that captures the parent exception, and the finally block should be behind all catch blocks

12. Precautions:

In general, do not use return or THORW in a finally block, such as the statement that causes the method to terminate, (throw), once the return or throw statement is used in the finally block, it will result in a try block, a return in the catch block, The Throw statement Fails.

When the program encounters a return or throw statement in the try/catch, the program stops executing, but does not immediately end the method, but rather finds whether it contains a finally block, and if there is no finally block, executes the return or throw statement immediately. Method terminates; If a finally block is available, the program starts executing the finally block immediately, and the system returns to the try block to execute a return or throw statement only if the statement in the finally block is executed If the finally block also contains a return or throw, which causes the method to end, the method is terminated in the finally block, and the program will no longer jump back to execute any code in the try block, catch block. In other words, the return statement in finally terminates the method prematurely.

13. Tip:

Minimizing the use of return,throw in the finally block can lead to some very special, imperceptible errors that are not conducive to program Development.

Big Data Java Foundation 14th Day

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.