Java Programming Thought study notes--12th through exception handling errors

Source: Internet
Author: User

The basic idea of Java is that "poorly structured code cannot run"

The ideal time to find an error is in the compile phase, which is before you try to run the program. However, no errors can be identified during compilation, and the remaining issues must be resolved during the run. This requires that the source of the error can somehow pass the appropriate information to a recipient----The recipient will know how to handle the problem correctly.

An exception condition is an issue that prevents the current method or scope from continuing to execute.

When an exception is thrown, there are a few things that can happen with it. First, as with the creation of other objects in Java, the exception object is created on the heap using new. The current execution path is then terminated, and a reference to the exception object is ejected from the current environment. At this point, the exception handling mechanism takes over the program and starts looking for an appropriate place to proceed with the execution of the program. The proper place is the exception handler, whose task is to recover the program from an error state so that the program will either run in another way or continue running.


Catching exceptions

try {

Code that might generate execptions

}


Exception handlers

try {

Code that might generate execptions

} catch (Type1 id1) {

Handle Execptions of Type1

} catch (Type2 Id2) {

Handle Execptions of Type2

}

etc...


Exception description

The exception description uses the additional keyword throws, followed by a list of all potential exception types, so the method definition might look like this:

However, if you write this:

void F () throws Toobig, Toosmall, Divzero {//...

means that this method does not throw any exceptions


Methods of Throwable of anomalous base class

String GetMessage ();

String Getlocalizedmessage ()

Used to get more information, or to express details in the local language.

String toString ();

Returns a brief description of the Throwable, which is included if there is more information.

void Printstacktrace ()

void Printstacktrace (PrintStream)

void Printstacktrace (Java.io.PrintWriter)

Prints the call stack traces for throwable and throwable. The call stack shows a sequence of method calls that "keep you there until the exception is thrown." The first version is output to a standard error, and the latter two allows you to select a stream to output

Throwable Fillinstacktrace ()

Used to record the current state of the stack frame inside the Throwable object. This is useful when a program re-throws an error or an exception

Alternatively, you can use Throwable to inherit from its base class object, which is the base class for all classes. For exceptions, GetClass () may be an easy-to-use method that returns an object representing this object type. You can then use the GetName () method to query the class object for the name of the package information, or to use the Getsimplename () method that produces only the class name.


Stack trajectory

The information provided by the Printstacktrace () method can be accessed directly through the Getstacktrace () method, which returns an array of elements in the stack trajectory, each of which represents a frame in the stack. Element 0 is the top element of the stack and is the last method call in the call sequence (where the throwable is created and thrown). The last element in the array and the bottom of the stack are the first method calls in the call sequence.


To re-throw an exception

If you simply re-throw the current exception object, the Printstacktrace () method will display the call stack information for the original exception throw point, rather than the information of the re-throw point. To update this information, call the Fillinstacktrace () method, which returns a Throwable object. It is created by filling in the current call stack information with the original exception object.

Exception chain

Often you want to throw another exception after catching an exception, and want to save the information of the original exception, which is called the exception chain.

Throwable subclasses can accept a cause (cause) object as a parameter in the constructor. This cause is used to represent the original exception by passing the original exception to the new exception, so that if a new exception is created and thrown at the current location, the exception chain can be traced to where the exception originally occurred.


Java Standard Exceptions

Throwable this Java class is used to represent any class that can be thrown as an exception. Throwable objects can be divided into two types (those that are inherited from Throwable): error is used to indicate compile-time and system errors (except in special cases, you are generally not concerned). Exception is a basic type that can be thrown, and a exception type exception can be thrown in Java class libraries, user methods, and runtime failures.


Exception: RuntimeException

RuntimeException exceptions or exceptions inherited from RuntimeException, it is not necessary to declare in the exception description that methods will throw exceptions of type runtimeexception, which are also referred to as "unchecked exceptions".


Use finally to clean up

Finally is always executed, and finally is used to clean up resources, including: open files or Web links, graphics on the screen, or even a switch in the outside world.


Limitations of exceptions

When overriding a method, only those exceptions listed in the exception description of the base class method can be thrown.


An important principle of exception handling is "Catch exceptions only if you know how to handle them."



Exception Usage Guide

Exceptions should be used in the following situations:

1) deal with the problem at the right level. (Catch an exception if you know what to do with it.) )

2) Resolve the problem and recall the method that generated the exception.

3) do a little patching and then go around the place where the exception occurred

4) Calculate with other data to replace the value expected to be returned by the method.

5) Put the current operating environment can do as far as possible last night, and then put the same exception to the higher level.

6) Try to finish what you can do in the current operating environment and throw the different exceptions to the higher level.

7) Termination procedure

8) to simplify. (If your abnormal pattern complicates the problem, it can be very painful and annoying to use.)

9) Make class libraries and programs more secure. (This is both a short-term investment in commissioning and a long-term investment in the robustness of the program)





This article is from the "Small City Ops" blog, please be sure to keep this source http://lixcto.blog.51cto.com/4834175/1911237

Java Programming Thought study notes--12th through exception handling errors

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.