Current location - Education and Training Encyclopedia - Education and training - Learn the methods and skills of Java programming?
Learn the methods and skills of Java programming?
Learning experience of Java exception

This paper mainly introduces some concepts of exception mechanism in Java. The purpose of writing this article is to facilitate me to recall these things quickly through this article when I forget it for a long time.

1. Exception mechanism

1. 1

Exception mechanism refers to how the program handles when an error occurs. Specifically, the exception mechanism provides a safe channel for the program to exit. When an error occurs, the process of program execution changes and the control of the program is transferred to the exception handler.

1.2

The traditional way to handle exceptions is that the function returns a special result to indicate that an exception has occurred (usually this special result is well known), and the program calling the function is responsible for checking and analyzing the results returned by the function. This has the following disadvantages: for example, the function returns-1, indicating that there is an exception, but if the function really returns the correct value of-1, there will be confusion; The readability is reduced, and the program code is mixed with the code that handles exceptions; The error analysis of the program calling this function requires the client programmer to have a deep understanding of the library function.

1.3 exception handling flow

1.3. 1 encountered an error, and the method ended immediately with no return value; At the same time, throw an exception object

1.3.2 The program calling this method will not continue to execute, but search for an exception handler that can handle this exception and execute the code in it.

2 Classification of anomalies

2. 1 Classification of anomalies

2. 1. 1

Inheritance structure of exceptions: the base class is Throwable, Error and exception inherit Throwable, RuntimeException and IOException, and the concrete RuntimeException inherits RuntimeException.

2. 1.2

Error and RuntimeException and their subclasses will be unchecked, while other exceptions will be checked.

2.2 Characteristics of each anomaly

2.2. 1 error system

The error class system describes the internal errors and resource exhaustion in the Java operating system. Applications should not throw this type of object (usually thrown by virtual machines). If this kind of error occurs, there is no alternative but to try your best to make the program exit safely. So when programming, we should pay more attention to abnormal systems.

Exception system

Abnormal systems include runtime abnormal systems and other non-runtime abnormal systems.

1 runtime exception

RuntimeException system includes wrong type conversion, array out-of-bounds access and attempt to access null pointer. The principle of handling RuntimeException is: If RuntimeException appears, it must be the programmer's fault. For example, you can avoid array out-of-bounds access exceptions by checking array subscripts and array boundaries.

2.2.2.2 others (IOException, etc. )

This kind of exception is usually an external error, such as trying to read data from the end of a file, which is not the error of the program itself, but the external error of the application environment.

2.3 different from C++ anomaly classification

2.3. 1

In fact, the class name RuntimeException in Java is not named correctly, because any exception occurs at runtime. Errors that occur at compile time are not exceptions, in other words, exceptions are designed to solve errors that occur at program run time.

2.3.2

Logic_error in C++ is equivalent to RuntimeException in Java, and runtime_error is equivalent to non-RuntimeException exception in Java.

3 abnormal use method

3. 1 The declaration method throws an exception.

3. 1. 1 Syntax: throws (abbreviation)

3. 1.2 Why does the declaration method throw an exception?

Whether a method throws an exception is as important as the type of the method return value. Assuming that the method throws an exception and it is not declared that the method will throw an exception, the client programmer can call the method without writing code to handle the exception. Then, once an exception occurs, there is no suitable exception controller to solve it.

3. Why does the exception thrown by1.3 have to be checked?

RuntimeException and Error can be generated in any code and do not need to be thrown by programmers. Once an error occurs, the corresponding exception will be automatically thrown. But checking exceptions is thrown by programmers, which can be divided into two situations: the client programmer calls the library function that will throw exceptions (the exception of the library function is thrown by the library programmer); The client programmer throws an exception by himself using the throw statement. When encountering errors, programmers are generally powerless; If you encounter RuntimeException, there must be a logical error in the program, and you need to modify the program (equivalent to a method of debugging); Programmers only care about checked exceptions, and programs should and should only throw or handle checked exceptions.

3. 1.4

Note: Subclass methods that override parent methods cannot throw more exceptions than parent methods. Therefore, when designing a parent class method, it is sometimes declared to throw an exception, but the code that actually implements the method does not throw an exception. The purpose of this is to make it easier for subclass methods to throw exceptions when overriding parent methods.

3.2 How to throw an exception

3.2. 1 Syntax: throw (abbreviation)

3.2.2 What exception is thrown?

For an abnormal object, the really useful information is the type of the abnormal object, and the abnormal object itself is meaningless. For example, if the type of the exception object is ClassCastException, then the class name is the only useful information. Therefore, when choosing what exception to throw, the most important thing is to choose a class whose class name can clearly explain the exception.

3.2.3

Abnormal objects usually have two kinds of constructors: one is a constructor without parameters; The other is a constructor with a string, which will be used as an additional description of this abnormal object in addition to the type name.

3.2.4

Create your own exception: When none of the built-in exceptions in Java can clearly explain the exception, you need to create your own exception. It should be noted that the only useful information is the type name, so don't spend your energy on the design of exception classes.

3.3 Capture exceptions

If an exception is not handled, then for a program with non-graphical interface, the program will be suspended and output exception information; For a graphical interface program, abnormal information will also be output, but the program will not stop, but will return to using "ы extension"? Hey? Small? BR & gt3.3. 1 Syntax: try, catch, finally (omitted)

The controller module must immediately follow the try block. If an exception is thrown, the exception control mechanism will search for the first controller whose parameters match the exception type, and then enter the catch.

Terms, and that the exception has been controlled. Once the catch clause ends, the search for the controller will also stop.

3.3. 1. 1 Catch multiple exceptions (pay attention to syntax and capture order) (omitted)

3.3. 1.2 Final usage and exception handling flow (omitted)

3.3.2 What does exception handling do?

For Java, due to garbage collection, exception handling does not need to recycle memory. But there are still some resources that programmers need to collect, such as files, network connections and pictures.

3.3.3 Should we declare that the method throws an exception or catch an exception in the method?

Principle: Catch and handle exceptions you know how to handle, and pass exceptions you don't know how to handle.

3.3.4 Throw an exception again.

3.3.4. 1 Why do you want to throw an exception again?

At this level, only a part of the content can be processed, and some processing needs to be completed in a higher-level environment, so an exception should be thrown again. This allows each level of exception handler to handle exceptions that it can handle.

3.3.4.2 exception handling process

Catch blocks corresponding to the same try block will be ignored, and the thrown exception will enter a higher level.

4 Other issues about anomalies

4. 1 Overuse exception

First of all, it is convenient to use exceptions, so programmers are generally no longer willing to write code to handle errors, but simply throw an exception. This is not right. For fully known errors, you should write code to deal with such errors and increase the robustness of the program. In addition, the efficiency of exception mechanism is very poor.

4.2 Distinguish between abnormal and common errors

For the same common mistakes, we should write code to deal with them and increase the robustness of the program. Only external runtime errors that cannot be determined and predicted need to use exceptions.

4.3 Information contained in abnormal objects

Usually, the only useful information of an exception object is the type information. However, when using a constructor with an exception string, the string can also be used as additional information. Call the getMessage (), toString () or printStackTrace () methods of the exception object to get the extra information of the exception object, the class name and the information of the call stack respectively. The latter contains a superset of the former.