Analysis of Java anomaly mechanism

Source: Internet
Author: User
Tags array length class definition instance method terminates throw exception

first, why to use the exception

The first thing we can make clear is that the exception handling mechanism can ensure the robustness of our program and improve the system availability rate. Although we do not particularly like to see it, but we can not recognize its status, role. There are exceptions to the problem of the program, help us to correct in time. In our program design, any time anywhere for any reason can be an exception, in the absence of an abnormal mechanism, we do this: the return value of the function to determine whether the exception (the return value is usually agreed to), the program called the function is responsible for checking and parsing the return value.

Although you can resolve the exception, there are several drawbacks to doing so:

1, easy to confuse. If the contract returns a value of-11111 indicates an exception, then when the final calculation of the program is really 1111?

2. Poor readability of code. Confusing the exception-handling code with the program code will reduce the readability of the code.

3, the call function to analyze the exception, which requires the programmer to have a deep understanding of library functions.

The exception handling mechanism provided in OO is a powerful way to provide code robustness.

Using the exception mechanism it can reduce the complexity of error handling code, and if you do not use exceptions, you must check for specific errors and handle them in many places in the program, and if you use exceptions, you do not have to check them at the method call, because the exception mechanism will ensure that the error is caught and Just deal with the error in one place, the so-called exception handler. This approach not only saves code, but also separates the code that outlines what to do during normal execution and what to do with the problem. In summary, the exception mechanism makes reading, writing, and debugging code more organized than the previous error-handling methods. (Excerpt from "Think in Java").

ii. Basic Definitions

In "Think in Java", this defines the exception:

An exception condition is an issue that prevents the current method or scope from continuing to execute. Here must be clear: The exception code a certain degree of error, although Java has an exception handling mechanism, but we can not be "normal" view of the exception, the exception handling mechanism is to tell you: here may or has produced an error, your program has been abnormal situation, may cause the program to fail!

So when will the anomaly occur?

Only in your current environment, the program will not function properly, that is, the program has not been able to solve the problem correctly, then it would jump out of the current environment, and throw an exception. After throwing an exception, it will first do a few things. First, it uses new to create an exception object, then terminates the program at the point where the exception was generated, and pops a reference to the exception object from the current environment. The exception handling mechanism takes over the program and starts looking for an appropriate place to continue executing the program, and the proper place is the exception handler, whose task is to recover the program from the wrong state so that the program either executes in a different way or continues execution.

In general, the exception handling mechanism is when the program is an exception, it forces the termination of the program to run, log the exception information and feedback to us, let us determine whether to handle the exception.

three. Java Exception class architecture

Exception refers to the various conditions, such as: file cannot be found, network connection failure, illegal parameters and so on. An exception is an event that interferes with the normal instruction flow during the program's run. Java describes various kinds of exceptions through the many subclasses of the Throwable class in the API. Thus, Java exceptions are objects, examples of throwable subclasses, and describe error conditions that occur in a piece of code. An error throws an exception when the condition is generated.

Java Exception class hierarchy diagram:

In Java, all exceptions have a common ancestor throwable (can be thrown). Throwable specifies the commonality of any problem that can be transmitted through a Java application using the exception propagation mechanism in the code.

Throwable:

There are two important subclasses: Exception (Exception) and error (Errors), both of which are important subclasses of Java exception handling, each of which contains a large number of subclasses.

Error (Errors):

is an error that the program cannot handle, indicating a more serious problem in running the application. Most errors are unrelated to what the code writer does, and represent a problem with the JVM (the Java virtual machine) that is running the code. For example, the Java Virtual machine runs the error (virtual Machineerror) and OutOfMemoryError occurs when the JVM no longer has the memory resources required to continue the operation. When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread.

These errors indicate that the failure occurred on the virtual machine itself, or when the virtual machine attempted to execute the application, such as a Java Virtual machine run error (virtual Machineerror), a class definition error (NOCLASSDEFFOUNDERROR), and so on. These errors are not available because they are outside the control and processing power of the application and are mostly not allowed when the program is running. For a well-designed application, even if it does, it should not be an attempt to deal with the anomalies that it causes. In Java, errors are described by the subclasses of the error.

Exception (Exception):

is an exception that the program itself can handle.

The Exception class has an important subclass runtimeexception. The RuntimeException class and its subclasses represent errors thrown by the JVM common operation. For example, if you attempt to use a null object reference, a divisor of zero, or an array out of bounds, a run-time exception is raised (nullpointerexception, ArithmeticException), and Arrayindexoutofboundexception.

Note: Exceptions and errors are different: Exceptions can be handled by the program itself, and errors cannot be handled.

In general, Java exceptions (including exception and error) are categorized as checked exceptions and non-checked exceptions (unchecked exceptions).

Exceptions can be checked (the compiler requires exceptions to be disposed of):

The correct program is in operation, it is easy to appear, reasonable can tolerate abnormal condition. Although the abnormal condition can be checked, it can be predicted to some extent, and in the event of such abnormal situation, it must be handled in some way.

in addition to RuntimeException and its subclasses, other exception classes and their subclasses belong to the exception-checking. This exception is characterized by the Java compiler checking it, that is, when such an exception can occur in a program, either by capturing it with a try-catch statement or by declaring it with a throws clause, or the compilation will not pass.

Exception not checked (compiler does not require forced disposition of exceptions):

includes run-time exceptions (RuntimeException with its subclasses) and errors (Error).

Four handling exception mechanisms

In a Java application, the exception handling mechanism is: Throw an exception, catch an exception.

Throw exception:

When a method throws an exception with an error, the method creates the exception object and delivers the runtime system, which contains exception information such as the type of the exception and the state of the program when the exception occurred. The runtime system is responsible for finding and executing the code that handles the exception.

Catching Exceptions:

After the method throws an exception, the runtime system will look for the appropriate exception handler (exception handler). A potential exception handler is a collection of methods that persist in the call stack, in turn, when an exception occurs. An appropriate exception handler is the exception type that can be handled by the exceptions handler when it matches the type of exception thrown by the method. The runtime system starts with the method in which the exception occurred and then turns back to the method in the call stack until it finds the method that contains the appropriate exception handler and executes it. The runtime system terminates when the runtime system traverses the call stack without finding an appropriate exception handler. At the same time, it means the termination of the Java program.

Java technology requires different exception handling for run-time exceptions, errors, or exceptions that can be checked.

Because of the non-availability of runtime exceptions, in order to make the application more reasonable and easier to implement, Java rules that runtime exceptions are automatically thrown by the Java runtime system, allowing applications to ignore runtime exceptions.

Java allows the method to not make any throw declarations when the run method does not want to catch the error that may occur in the method's run. Because most error exceptions belong to a condition that can never be allowed to occur, it is also a reasonable exception that the application should not catch.

For all the exceptions that can be checked, the Java rule is that a method must catch, or declare the throw method. That is, when a method chooses not to catch an exception, it must declare that it will throw an exception.

The ability to catch exceptions requires a matching type of exception handler. The exception that is caught may be an exception that is thrown by an individual statement, or an exception that is thrown by a method called or by the Java Runtime System.

In other words, the exception that a method can catch must be the exception that Java code throws on the premises. Simply put, the exception is always first thrown and then captured.

Five. Common Java Exceptions1. RuntimeException Sub-Category:

1, Java.lang.ArrayIndexOutOfBoundsException
Array index out-of-bounds exception. Thrown when the index value of an array is negative or greater than or equal to the size of the arrays.

2, Java.lang.ArithmeticException
Arithmetic condition exception. For example: integers except 0.

3, Java.lang.NullPointerException
Null pointer exception. This exception is thrown when an app tries to use null where the object is required. Example: Invoking an instance method of a null object, accessing the properties of a null object, calculating the length of a null object, throwing null with a throw statement, and so on

4, Java.lang.ClassNotFoundException
The class exception could not be found. This exception is thrown when an application attempts to construct a class based on a class name in string form, and when a class file of the corresponding name is not found after traversing Classpah.

5, java.lang.NegativeArraySizeException array length is negative exception

6. Exceptions thrown by incompatible values in the Java.lang.ArrayStoreException array

7. Java.lang.SecurityException Security exception

8. Java.lang.IllegalArgumentException Illegal parameter exception

2.IOException

IOException: An exception that may occur when manipulating input and output streams.

Eofexception file has ended exception

FileNotFoundException File not found exception

3. Other

ClassCastException type Conversion Exception class

Arraystoreexception an exception that is thrown in an array that contains incompatible values

SQLException Manipulating Database Exception classes

nosuchfieldexception Field not found exception

The Nosuchmethodexception method did not find the thrown exception

NumberFormatException string conversion to a number thrown exception

Stringindexoutofboundsexception string index out of range throw exception

Illegalaccessexception does not allow access to a class of exceptions

Instantiationexception when an application attempts to create an instance of a class using the Newinstance () method in the class classes, and the specified class object cannot be instantiated, the exception is thrown

Analysis of Java anomaly mechanism

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.