A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service
This article focuses on some concepts of exception mechanisms in Java. The purpose of this article is to make it easy for me to remember these things quickly after a long time.
1. Abnormal mechanisms
The 1.1 exception mechanism refers to how the program is handled when an error occurs. Specifically, the exception mechanism provides a secure channel for the program to exit. When an error occurs, the process of executing the program changes, and the control of the program is transferred to the exception handler.
1.2 The traditional method of dealing with exceptions is that the function returns a special result to indicate an exception (usually this particular result is commonly called), and the program that calls the function is responsible for checking and analyzing the result of the function return. There are drawbacks to doing this: for example, function return-1 represents an exception, but it's confusing if the function does return the correct value of 1--the readability is reduced, the program code is mixed with the code that handles the exception; The program that invokes the function analyzes the error, which requires the client programmer to have a deep understanding of the library function.
1.3 Process of exception handling
1.3.1 encounters an error, the method ends immediately, does not return a value, and throws an exception object
1.3.2 The program that calls the method does not continue, but instead searches for an exception handler that can handle the exception and executes the code
2 Classification of exceptions
2.1 Classification of exceptions
Inheritance structure for 2.1.1 Exceptions: The base class inherits ioexception such as Throwable,runtimeexception and exception for Throwable,error and exception, The concrete runtimeexception inherits RuntimeException.
2.1.2 Error and RuntimeException and subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).
2.2 Characteristics of each type of anomaly
The 2.2.1 Error system describes the internal errors in the Java running system and the situation of resource exhaustion. Applications should not throw objects of this type (typically thrown by a virtual machine). In the event of such a mistake, in addition to trying to secure the program out of the way, there is nothing else to do. Therefore, in the design, we should pay more attention to the exception system.
Exception system of 2.2.2 Exception system including RuntimeException system and other non-runtimeexception system
The 220.127.116.11 runtimeexception runtimeexception system includes incorrect type conversions, array access across arrays, and attempts to access null pointers, and so on. The principle of dealing with runtimeexception is that if there is a runtimeexception, it must be the programmer's fault. For example, you can avoid array-crossing access exceptions by examining the array subscripts and arrays of boundaries.
18.104.22.168 other (IOException et cetera) such exceptions are generally external errors, such as trying to read data from the end of a file, and so on, which is not an error in the program itself, but an external error that occurs in the application environment.
2.3 different from C + + exception classification
2.3.1 In fact, the class name RuntimeException in Java is not appropriate, because any exception is runtime. (the error that occurs at compile time is not an exception, in other words, the exception is to resolve the error that occurs when the program is run.)
In 2.3.2 C + +, Logic_error is equivalent to the runtimeexception in Java, and Runtime_error is equivalent to Java-runtimeexception type exceptions.
3 How to use exceptions
3.1 Declaring method throws an exception
3.1.1 Syntax: throws (abbreviated)
3.1.2 Why do you want to declare a method throw an exception? Whether a method throws an exception is as important as the type of the method return value. Suppose the method throws an exception without declaring that the method will throw an exception, then the client programmer can call this method and do not have to write code to handle the exception. Then, once an exception occurs, there is no suitable exception controller to resolve the exception.
3.1.3 Why the exception that was thrown must have been checked for exceptions? RuntimeException and error can be generated in any code, they do not need to be thrown by the programmer, and when an error occurs, the corresponding exception is automatically thrown. Check exceptions are thrown by the programmer, which is divided into two cases: a client programmer invokes a library function that throws an exception (the exception for the library function is thrown by the library programmer); The client programmer uses the throw statement to throw the exception himself. Encounter error, programmers are generally powerless; encountered RuntimeException, then must be the program has a logic error, to modify the program (equivalent to a method of debugging); Only checked exceptions are the programmer's concern, and the program should and should only throw or handle checked exceptions.
3.1.4 Note: A subclass method that overrides a method of the parent class cannot throw more exceptions than the parent class method. As a result, sometimes the method of designing a parent class declares an exception to be thrown, but the actual implementation method's code does not throw an exception, in order to make it easier for the subclass method to override the parent class method to throw an exception.
3.2 How to throw an exception
3.2.1 Syntax: throw (abbreviated)
What exception does 3.2.2 throw? For an exception object, the truly useful information is the object type of the exception, and the exception object itself is meaningless. For example, the type of an exception object is ClassCastException, and the class name is the only useful information. Therefore, when choosing what exceptions to throw, the most important thing is to select the class name of the exception that can clearly describe the exception.
3.2.3 Exception objects usually have two constructors: one is a parameterless constructor, the other is a constructor with a string that will serve as an extra description of this exception object in addition to the type name.
3.2.4 Create your own exception: you need to create your own exception when the Java built-in exception does not explicitly describe the exception. It's important to note that the only thing that is useful is the type name information, so don't expend your energy on the design of the exception class.
3.3 Catch Exception If an exception is not processed, then for a non graphical interface program, the program will be aborted and output exception information, for a graphical interface program, but also output exception information, but the program does not abort, but return to the user interface processing loop.
3.3.1 syntax: Try, catch, and finally (abbreviated) controller modules must be immediately following the try block. If an exception is thrown, the exception control mechanism searches for the first controller that matches the type of the exception and then it enters the catch clause and considers the exception to be controlled. Once the catch clause ends the search for the controller will also stop.
22.214.171.124 Catch multiple exceptions (note syntax and capture Order) (abbreviated)
126.96.36.199 finally usage and exception handling process (abbreviated)
What does 3.3.2 exception handling do? For Java, exception handling does not need to reclaim memory because of garbage collection. But there are still resources to be collected by programmers, such as files, Internet connections, and pictures.
Should 3.3.3 declare a method throw an exception or catch an exception in a method? Principle: Catching and handling exceptions that know how to handle, and passing exceptions that don't know how to handle
3.3.4 throws an exception again
Why should 188.8.131.52 throw the exception again? In this level, only part of the content can be processed, some processing needs to be done in a higher level environment, so the exception should be thrown again. This allows the exception handler at each level to handle the exception that it can handle.
The 184.108.40.206 exception handling process corresponds to a catch block with the same try block that will be ignored, and the thrown exception will enter a higher level.
4 other questions about the exception
4.1 Overuse exceptions first, it's convenient to use exceptions, so programmers are generally no longer willing to write code that handles errors, but simply throw an exception. This is not true, for fully known errors, you should write code to handle this error and increase the robustness of the program. In addition, the efficiency of the anomaly mechanism is very poor.
4.2 Separating the exception from the normal error area for common, completely consistent errors, you should write code to handle this error and increase the robustness of the program. Exceptions need to be used only for external, unpredictable and predictable run-time errors.
4.3 information contained in exception objects in general, the only useful information for an exception object is type information. However, this string can also be used as additional information when using a constructor with an exception with a string. The GetMessage (), toString (), or Printstacktrace () method of an exception object can be invoked separately for additional information about the exception object, the class name, and the call stack. And the latter contains the information that is the previous superset.
Unsupportedoperationexception Operations not supported
IllegalArgumentException Illegal parameters
Indexoutofboundsexception index out of bounds
IllegalStateException Illegal State
There is a certain difference between an exception and an ordinary warning. When an exception is encountered in an application, the normal instruction stream of the executing program is interrupted. That is, the code that follows the exception will not be properly executed. It can even trigger a fallback operation for the database.
In the Java development platform, exceptions include predefined exceptions and custom exceptions. The types of these two exceptions complement each other. As a qualified program developer, be adept at using exceptions in your application. This can increase the interactivity of your application. At the same time, it is also a prerequisite to ensure the normal operation of the application. Therefore, exception handling is very important for developing a good application. For this reason, the author thinks that the program developers should have a deep understanding of the common exceptions of Java applications. The handling of custom exceptions can be done only if you understand these common anomalies.
I. Types and causes of common anomalies.
For common exceptions to Java applications, the author believes that program developers need to learn from two aspects. One is to know what common Java application exceptions are, and the second is to know what might be causing the exception. This not only requires program managers to pay attention to accumulation in their daily work, but also need to collect data from other channels when necessary. The author of this on an analysis, I hope to be able to program developers have some help.
1, SQLException: Operation Database Exception class.
Most Java applications now depend on the database running. This class is triggered when an error occurs when a Java application communicates with the database. The error message for the database is also displayed to the user through this class. In other words, this operation database exception class is a bridge between database and user's abnormal information transmission. If the user is now inserting data into the system, a field must be specified in the database to be unique. When the user inserts the data, if the value of this field repeats with the existing record, violates the database uniqueness constraint, at this time the database will run out an exception information. This information may not be visible to the general user because it occurs at the database level. At this point the Operation database exception class will capture the database of this exception information, and the exception information passed to the foreground. In this way, the foreground user can analyze the cause of the error based on this exception information. This is the main purpose of this operation database exception class. In a Java application, this class is triggered when an exception occurs for all database operations. All of this time the Java application itself is often too general information, only to say that the database interaction errors, not much reference value. At this point instead is the database of the hint information more useful value.
2, ClassCastException: Data type conversion exception.
In Java applications, it is sometimes necessary to convert data types. This transformation includes the conversion of the display and the implicit conversion. However, no matter how the conversion, must meet a prerequisite conditions, that is, the compatibility of data types. If this principle is violated during data conversion, a data type conversion exception is triggered. Now, in an application, developers need to convert a character date data to date data that the database is able to accept, which requires only control in the foreground application, generally without problems. However, if the foreground application lacks relevant controls, such as when the user enters a date with only month, day information, and no year information. At this point, an exception occurs when the application is converting to a data type. According to the author's experience, the data type conversion exception in the application development to make a more occurrence of the exception, but also a relatively low-level exception. Because in most cases, you can enforce some control over the data type in the application window. That is, the data type is guaranteed to be compatible before the data type is converted. In this case, it is not easy to cause a conversion exception for the data type. In fields that allow only numeric types, you can set characters that do not allow users to enter numeric values. Although there is an exception handling mechanism, you can guarantee that the application will not be run incorrectly. But in the actual development, still have to anticipate the reason that the error occurs as much as possible, avoid unusual occurrence as far as possible.
3, NumberFormatException: The exception that is thrown when the string is converted to a numeric type.
In the process of data type conversion, if it is the problem that the character type converts to the digital type, for this exception, a separate exception is used in the Java program, that is, numberformatexception. If the character-typed data "123456" is now converted to numeric data, is allowed. However, if character data contains non-numeric characters, such as 123#56, an exception occurs when converting to a numeric type. The system catches the exception and processes it.
There are a number of exception classes that are common in Java applications. If the corresponding class exception is not found, some class exceptions are not allowed, the file has ended an exception, the file is not found, the field is not found, and so on. General system developers can determine the type of the current exception based on this exception name. Although good, but good memory than bad pen. The program developer, when necessary (especially when there is a custom exception), has an exception schedule at hand. In this case, whether the application in the debugging process to find problems, or the operation of the user received complaints, can be timely according to the exception name to find the cause of the anomaly. This allows you to resolve exceptions in the shortest possible time and restore the normal operation of your application. This measure I used for many years, very effective.
Second, the practical suggestion of abnormal management.
The Java application provides only one exception class for manipulating database exceptions. Therefore, the error message of the Java application is often not able to help the application personnel to troubleshoot the cause of the error. The exception that can only be named is an application error or a database error. To further identify the cause of the problem, it is best to illustrate the specific cause when defining an exception at the database level. For example, the foreground application might call a database function or procedure. At this point in the database function or process to do a description of the specific reason for an exception. If another table is generated from one of the underlying tables, a field cannot be empty, and so on. When these exception information is clearly explained, if a similar exception is encountered, the operation of the database exception class will counter the abnormal information of the database to the foreground user. In order to help users find the cause of the problem, and in the shortest possible time to correct. Of course, this requires a Java programmer to coordinate with the Database Designer.
The second thing to note is that anomalies are not normal. In other words, most of the anomalies can be eliminated by the reasonable foresight and prevention of the premises. If you design to arithmetic, you can limit the number of entries in the Foreground application window to 0 values in addition to the digital section to eliminate possible exceptions in the application's operation. However, this often requires application developers to have a wealth of work experience as well as more rigorous thinking logic. Although this has a certain degree of difficulty, but the author believes that the program developers should still work on this, rather than always let users as your test, so that users can discover the application of design bugs. The author thinks that only some factors that are beyond the control of the program personnel are allowed to throw exceptions. The author is not allowed if the application developer is aware of this error, but is still not paying attention or taking effective measures to prevent this anomaly.
ArithmeticException (an exception with a divisor of 0), bufferoverflowexception (buffer overflow exception), bufferunderflowexception (buffer underflow exception), Indexoutofboundsexception (out of Bounds), nullpointerexception (null-pointer exception), Emptystackexception (empty stack exception), IllegalArgumentException (illegal parameter anomalies), Negativearraysizeexception, Nosuchelementexception, SecurityException, SystemException, Undeclaredthrowableexception
The exception is interpreted as "a program encounters a null pointer", simply by invoking an uninitialized object or an object that does not exist, confusing the initialization of the array and initializing the elements. The initialization of an array is the space needed to allocate the arrays, and the initialized array, the elements of which are not instantiated, are still empty, and therefore each element needs to be initialized (if it is to be invoked)
The exception is interpreted as "The specified class does not exist."
The explanation for this exception is "mathematical arithmetic", such as an exception that occurs in a program that is divided by 0.
The exception is interpreted as "array subscript out of bounds", now most of the program has the operation of the array, so in the call to the arrays must be carefully checked to see if the subscript you call is beyond the scope of the array, in general, the display (that is, directly with the constant current standard) call is not too easy to make such a mistake, But the implicit (that is, variable representation of the subscript) call is often wrong, there is a case, the program is defined in the length of the array is determined by some specific methods, not in advance, this time, it is best to look at the length of the array, so as to avoid this exception.
The explanation for this exception is "parameter errors of the method", such as the three values in the method of G.setcolor (int red,int green,int blue), and if there are more than 255, this exception will occur, so once this anomaly is found, what we're going to do, Just go check it out. The argument passing in the method call is not an error.
This exception is interpreted as "no access", which occurs when the application calls a class, but the current method does not have access to the class. Pay attention to this exception if you use package in your program
, exceptions, Java
Thank you for reading, I hope to help you, thank you for your support for this site!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service