Java Programming Ideas Learn Note 12

Source: Internet
Author: User
Tags throwable

12. Error handling by exception

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

The purpose of exception handling in Java is to simplify the generation of large, reliable programs by using less than the current amount of code, and this way you can make yourself more confident: There are no unhandled errors in your program.

1. Concept  

C and other early languages often have multiple error-handling patterns that are often built on a conventional basis and are not part of the language. Usually returns a special value or sets a flag, and assumes that the recipient will check the return value or flag to determine if an error has occurred. However, this error-handling pattern has become a major impediment to the construction of large, robust, maintainable programs.

The solution is to use a mandatory form to eliminate arbitrary factors in the error handling process. This is a long-standing practice, and the implementation of exception handling can be traced back to the the 1960s operating system, even the on error Goto statement in the basic language. While the exception handling mechanism of C + + is based on Ada, exception handling inJava is built on C + + .

A fairly obvious benefit of using exceptions is that it tends to reduce the complexity of error-handling code. If you do not use an exception, you must check for a specific error and handle it in many places in the program. If you use an exception, you do not have to check at the method call, because the exception mechanism guarantees that the error will be caught. And, just one place to handle the error, the so-called exception handler. This approach not only saves code, but also separates the code that describes what to do during normal execution and what to do with the problem.

  

2. Basic Exceptions  

An exception condition is an issue that prevents the current method or scope from continuing to execute. It is important to differentiate between anomalies and common problems, and the so-called common problem is that you can get enough information in the current environment to handle this error. In the case of anomalies, you cannot continue because you cannot get the necessary information to solve the problem in the current environment. All you can do is jump out of the current question and submit the problem to the upper-level environment. This is what happens when you throw an exception.

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 can either run in a different way or continue running.

  ① Exception Parameters

All standard exception classes have two constructors: one is the default constructor, and the other is to accept the string as a parameter so that the relevant information can be placed in the constructor of the exception object.

Typically, the only information in an exception object is the exception type, except that it does not contain any meaningful content.

3. Catching exceptions  

To understand how exceptions are captured, you must first understand the concept of the monitoring area. It is a piece of code that might produce an exception, followed by the code that handles those exceptions.

  ①try Block

If an exception is thrown inside the method, the method ends in the process of throwing an exception. If you do not want the method to end, you can set a special block inside the method to catch the exception. Because in this block "try" various method calls, it is called a try block.

Try {     //here' s the Code       }

  ② Exception Handling Program

The exception handler is immediately following the try block, represented by a keyword catch.

4. Create a custom exception  

To define an exception class yourself, you must inherit from an existing exception class, preferably by selecting an exception class that has a similar meaning.

The most important part of an exception is the class name.

5. Exception description

The exception description is part of the method declaration, immediately following the formal parameter list.

6. Catch all exceptions

You can write only one exception handler to catch all types of exceptions. This can be done by capturing the base class of the exception type Exception .

  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.

  Exception chain

  Often you want to throw another exception after catching an exception, and want to keep the information of the original exception, which is called the exception chain. Now all Throwable subclasses can accept a 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.

Only three basic exception classes provide constructors with cause parameters, namely Error,Exception , and runtimeexception. If you want to link other types of exceptions, you should use the Initcause () method instead of the constructor.

  

7.Java Standard exception

The Throwable class is used to represent any class that can be thrown as an exception. There are two types of Throwable objects: error is used to denote compile-time and system errors, and exception is the basic type that can be thrown. The base types that Java programmers care about are usually exception.

The basic concept of an exception is to use the name to represent the problem that occurs, and the name of the exception should be able to look at the text.

  ① Special case: RuntimeException

Runtime exceptions are automatically thrown by the Java Virtual machine and are referred to as "unchecked exceptions".

If the runtimeexception is not captured and goes directly to main (), the exception's Printstacktrace () method is called before the program exits.

  The RuntimeException represents a programming error:

1) Unexpected error. For example, a null reference

2) as a programmer, you should check the code for errors.

8. Use finally to clean up

The code in the finally clause always runs, regardless of whether the exception in the try block is thrown.

When you want to restore resources other than memory to their initial state, you need to use the finally clause. Resources that need to be cleaned up include open files or network connections, graphics on the screen, or even a switch from the outside world.

The finally clause is also executed when the break and continue statements are involved.

When the finally clause is used in some special way, an exception is lost. For example, return in the finally clause.

9. Limitations of exceptions

When overriding a method, only those exceptions listed in the exception description of the base class method can be thrown. This means that when the code used by the base class is applied to its derived class object, it works as well as the exception.

The exception limit has no effect on the constructor. However, the exception description for the derived class constructor must contain the exception description for the base class constructor. The derived class constructor cannot catch exceptions thrown by the base class constructor.

Methods cannot be overloaded based on exception descriptions. An exception that appears in the exception description of the base class method does not necessarily appear in the exception description of the derived class method.

10. Constructors

For classes that may throw exceptions during the construction phase and require cleanup, the safest way to use them is to use nested try clauses.

11. Exception Matching  

When an exception is thrown, the exception handling system finds the "most recent" handler in the order in which the code is written. After a matching handler is found, it considers the exception to be handled and the lookup no longer continues.

The object of a derived class can also match the handler for its base class.

12. Exception Usage Guide

1) deal with the problem at the right level.

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) Try to finish what you can do in the current operating environment and throw the same or different exceptions to the higher level.

6) terminate the program.

7) to simplify.

8) Make class libraries and programs more secure.

13. Summary The above is a lot of things, many more complicated problems are not two words.

Exceptions can help us create more robust programs, which are important and less complex. Should be proficient in mastering

Java Programming Ideas Learn Note 12

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.