Java Common exceptions

Source: Internet
Author: User

This article focuses on some concepts of exception mechanisms in Java. The purpose of writing this article is to help me remember these things quickly after a long time. 1. Exception mechanism 1.1 The exception mechanism refers to how the program handles an error. Specifically, the exception Mechanism provides a secure channel for program exit. When an error occurs, the execution process of the program changes, and the control of the program is transferred to the exception processor. 1.2 The traditional way to handle exceptions is that the function returns a special result to indicate exceptions (this special result is usually agreed ), the program that calls this function is responsible for checking and analyzing the results returned by the function. This method has the following drawbacks: for example, if the function returns-1, it indicates an exception, but if the function does want to return the correct value of-1, it will be confused; the readability is reduced, the program code is mixed with the code that handles exceptions. The program that calls the function analyzes errors, which requires the client programmer to have a deep understanding of the library functions. 1.3 exception handling process 1.3.1 when an error occurs, the method ends immediately and does not return a value. At the same time, the program that throws an exception object 1.3.2 to call this method will not continue to execute, instead, search for an exception processor that can handle the exception and execute code 2 exception classification 2.1 exception classification 2.1.1 inheritance structure of the exception: the base class is Throwable, errors and exceptions inherit from Throwable, RuntimeException, and IOException. Specific RuntimeException inherits from RuntimeException. 2.1.2 Error, RuntimeException, and its subclass become unchecked, and other exceptions become checked ). 2.2 characteristics of each type of exception 2.2.1 Error system Error class system describes internal errors in the Java operating system and resource depletion. Applications should not throw such objects (usually thrown by virtual machines ). In addition to trying to secure the exit of the program, this error is not feasible in other aspects. Therefore, when designing programs, we should pay more attention to the Exception system. 2.2.2 Exception system the Exception system includes the RuntimeException system and other non-RuntimeException systems 2.2.2.1 the RuntimeException system includes incorrect type conversion, array out-of-bounds access, and attempts to access null pointers. The principle for processing RuntimeException is: If RuntimeException occurs, it must be a programmer error. For example, you can check the array subscript and array boundary to avoid array out-of-bounds access exceptions. 2.2.2.2 other (IOException, etc.) exceptions are generally external errors, such as attempts to read data from the end of a file. This is not a program error, an external error occurs in the application environment. 2.3 different from C ++ exception classification 2.3.1 in fact, RuntimeException in Java is not appropriate because any exception occurs at runtime. (The errors that occur during compilation are not exceptions. In other words, exceptions are used to solve the errors that occur during the program running ). 2.3.2 logic_error in C ++ is equivalent to RuntimeException in Java, while runtime_error is equivalent to non-RuntimeException type exceptions in Java. 3. How to Use exceptions 3.1 declaration method throw an exception 3.1.1 Syntax: throws (Omitted) 3.1.2 why should I declare a method to throw an exception? Whether a method throws an exception is as important as the type of the method return value. If the method throws an exception and does not declare that the method throws an exception, the client programmer can call this method without writing code to handle the exception. In this case, once an exception occurs, no suitable exception controller can be used to solve the exception. 3.1.3 why must I have checked the thrown exception? RuntimeException and Error can be generated in any code. They do not need to be thrown by the programmer. Once an Error occurs, the corresponding exception is automatically thrown. The check exception is thrown by the programmer. There are two situations: the client programmer calls the library function that throws an exception (the Library Function exception is thrown by the library programmer ); the client programmer throws an exception using the throw statement. When an Error occurs, programmers are generally powerless. When a RuntimeException occurs, the program must have a logic Error and must be modified (equivalent to a debugging method ); only the checked exceptions are the concern of the programmer. The program should and should only throw or handle the checked exceptions. 3.1.4 Note: The subclass method that overwrites a method of the parent class cannot throw more exceptions than the parent class method. Therefore, when designing a method of the parent class, it is declared to throw an exception, however, the Code of the actual implementation method does not throw an exception, so that the subclass method can throw an exception when overwriting the parent class method. 3.2 how to throw an exception 3.2.1 Syntax: throw (Omitted) 3.2.2 What exception is thrown? For an exception object, the object type is abnormal when the information is really useful, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, this class name is the only useful information. Therefore, when selecting an exception to be thrown, the most important thing is to select the exception class name to clearly indicate the exception. 3.2.3 an exception Object usually has two constructor types: one is a constructor without parameters, and the other is a constructor with a string, this string will be used as an additional description for this exception object except for the type name. 3.2.4 create your own exceptions: When Java built-in exceptions do not explicitly indicate exceptions, you need to create your own exceptions. It should be noted that the only useful information is the type name, so do not spend effort on the design of the exception class. 3.3 capture exceptions if an exception is not handled, the program will be aborted and output exception information for a non-graphic program. For a graphic interface program, it also outputs the exception information, but the program does not stop, but returns to the user interface processing loop. 3.3.1 Syntax: The try, catch, and finally (slightly) controller modules must be followed by the try block. If an exception is thrown, the exception Control Mechanism searches for the first controller whose parameters match the exception type. Then it enters the catch clause and considers that the exception has been controlled. Once the catch clause ends, the search for the Controller will also stop. 3.3.1.1 capture multiple exceptions (note the syntax and capture sequence) (Omitted) 3.3.1.2 finally usage and exception handling process (Omitted) 3.3.2 what is the exception handling process? For Java, due to garbage collection, the memory does not need to be recycled for exception handling. However, there are still some resources that need to be collected by programmers, such as files, network connections and images. 3.3.3 should I declare whether the method throws an exception or catch an exception in the method? Principle: capture and handle exceptions that know how to handle, and pass exceptions that do not know how to handle 3.3.4 throw an exception again 3.3.4.1 why should we throw an exception again? At this level, only a part of the content can be processed. Some processing needs to be completed in a higher-level environment, so an exception should be thrown again. In this way, the exception processor at each level can handle the exceptions that it can handle. 3.3.4.2 the catch Block corresponding to the same try block in the exception handling process will be ignored, and the thrown exception will enter a higher level. 4. Other exceptions 4.1 excessive use of exceptions first, it is very convenient to use exceptions, so programmers are generally no longer willing to write code to handle errors, rather than simply throwing an exception. This is wrong. For completely known errors, you should write the code to handle such errors to improve the robustness of the program. In addition, the exception mechanism is inefficient. 4.2 differentiate exceptions from common errors. For common errors that are exactly the same, you should write the code to handle these errors to improve the robustness of the program. An exception is required only for unknown and unexpected running errors. 4.3 The information contained in the exception object. Generally, the only useful information of the exception object is the type information. However, when a constructor with an exception string is used, this string can also be used as additional information. You can call the getMessage (), toString (), or printStackTrace () Methods of an exception object to obtain additional information about the exception object, class name, and call stack information. In addition, the information contained in the latter type is the superset of the former type. Common exceptions: The operation IllegalArgumentException is not supported by UnsupportedOperationException. The invalid IndexOutOfBoundsException is different from the normal warning. When an application exception occurs, the normal Command Flow of the program being executed is interrupted. That is to say, the code after an exception cannot be correctly executed. It even triggers the database rollback operation. On the Java Development Platform, exceptions include pre-defined exceptions and custom exceptions. These two types of exceptions complement each other. As a qualified program developer, be good at using exceptions in applications. This improves the interaction of applications. It is also a prerequisite for ensuring the normal operation of applications. Therefore, exception handling is very important for developing an excellent application. For this reason, I believe that developers should have an in-depth understanding of common exceptions of Java applications. You can handle custom exceptions only when you understand these common exceptions. 1. Common types and causes of exceptions. For the common exceptions of Java applications, the author thinks that developers should understand them from two aspects. First, you need to know the common Java application exceptions, and second, you need to know the causes that may cause this exception. This not only requires the program management personnel to pay attention to accumulation in their daily work, but also to collect data from other channels if necessary. The author makes an analysis on this and hopes to help developers. 1. SQLException: Database exception class. Currently, most Java applications depend on databases. This class is triggered if an error occurs when the Java application communicates with the database. At the same time, the database error information is displayed to the user through this class. That is to say, this database exception class is a bridge between the database and the user for exception information transmission. For example, if a user inserts data into the system, a field must be unique in the database. When a user inserts data, if the value of this field is repeated with the existing record, it violates the uniqueness constraints of the database, and then the database runs out an exception message. This information is generally invisible to users because it occurs at the database level. In this case, the exception class of the database will capture the exception information of the database and pass the exception information to the foreground. In this case, the foreground user can analyze the cause of the Error Based on the exception information. This is the main purpose of this database exception class. In Java applications, this class is triggered when all database operations are abnormal. At this time, the prompt information of the Java application itself is often too general. It only means that there is an error in interacting with the database, which has little reference value. In this case, the prompt information of the database is more useful. 2. ClassCastException: data type conversion exception. In Java applications, data types sometimes need to be converted. This conversion includes explicit conversion and implicit conversion. However, no matter how it is converted, it must comply with a prerequisite, that is, the compatibility of data types. If this principle is violated during data conversion, a data type conversion exception is triggered. For example, in applications, developers need to convert a stable date data to the date data that the database can accept. In this case, they only need to control the data in the foreground application, generally, no problem occurs. However, if the foreground application lacks relevant control, for example, when you enter a date, you only enter the month and day information, but not the year information. In this case, an exception occurs when the application converts data types. Based on my experience, the exception of data type conversion is also a low-level exception in application development. In most cases, you can forcibly control the data type in the application window. This ensures the compatibility of data types before data type conversion. In this case, it is not easy to cause data type conversion exceptions. For example, in a field that only supports the value type, you can set a character that does not allow the user to enter a value. Although the exception handling mechanism is available, it can ensure that the application will not be run incorrectly. However, in actual development, we still need to anticipate as many causes of errors as possible and avoid exceptions as much as possible. 3. NumberFormatException: The exception thrown when the string is converted to the numeric type. In the process of data type conversion, if the numeric type is converted to the numeric type, an independent exception is used in the Java program, that is, NumberFormatException. for example, it is allowed to convert the numeric data "123456" to the numeric data. However, if the numeric data contains non-numeric characters, such as 123 #56, an exception occurs when it is converted to a numeric data type. The system will capture this exception and handle it. There are many common exception classes in Java applications. For example, the corresponding class exception is not found, some class exceptions are not allowed to be accessed, the file has ended, the file has not been found, and the field has not been found. Generally, system developers can determine the type of the current exception based on the Exception name. Although good, good memory is not as bad as writing. When necessary (especially when a custom exception exists), the program developer finally has an exception schedule. In this case, you can find the cause of the exception based on the Exception name in time, whether the application finds a problem during debugging or receives a user complaint during running. The exception can be solved in the shortest time to restore the normal operation of the application. This measure has been used for many years and is very effective. Ii. practical suggestions for exception management. Java applications only provide one exception class for operating database exceptions. Therefore, errors of Java applications often fail to help application personnel eliminate the cause of errors. Only the application errors or database errors can be identified. To further identify the cause of the problem, it is best to explain the specific cause when defining an exception at the database level. For example, foreground applications may call database functions or processes. In this case, the specific cause of an exception can be explained in the database function or process. For example, when another table is generated based on a base table, a field cannot be blank. After the exception information is clearly described, if a similar exception is encountered, the exception information of the database will be reversed to the foreground user. This helps you find the cause of the problem and correct it in the shortest time. Of course, this requires coordination between Java programmers and database designers. Note that exceptions are not normal. That is to say, most exceptions can be eliminated through reasonable premise foresight and prevention. If four arithmetic operations are designed, You can restrict the input of 0 in the divisor field in the foreground application window to eliminate possible exceptions in the application program. However, this usually requires application developers to have a wealth of work experience and strict thinking logic. Although this is difficult, the author believes that developers should continue to work in this area, rather than always let users as your experimental products, so that users can discover Design Bugs in applications. I believe that only some factors beyond the control of programmers can throw exceptions. If the application developers are aware of this error, but still do not pay attention to it or take effective measures to prevent such exceptions, I am not allowed. ArithmeticException (exception with a division of 0), BufferOverflowException (buffer overflow exception), BufferUnderflowException (buffer overflow exception), writable (out-of-bounds exception), NullPointerException (NULL pointer exception ), emptyStackException (empty stack exception), IllegalArgumentException (invalid parameter exception), NegativeArraySizeException, NoSuchElementException, SecurityException, SystemException, UndeclaredThrowableException 1. java. lang. the NullPointerException exception is interpreted as "the program encounters a null pointer", which is simply called The initialization of the array and the initialization of the array elements are confused. Array initialization allocates the required space to the array. The elements in the initialized array are not instantiated and are still empty, therefore, you also need to initialize each element (if you want to call it. java. lang. the ClassNotFoundException exception is interpreted as "the specified class does not exist ". 3. The exception of java. lang. ArithmeticException is interpreted as a "mathematical operation exception". For example, if a division by zero operation occurs in a program, this exception occurs. 4. java. lang. the ArrayIndexOutOfBoundsException exception is interpreted as "array subscript out of bounds". Currently, most programs operate on arrays. Therefore, you must check the array before calling it, check whether the subscript you call is beyond the range of the array. In general, it is not easy to make such an error when calling (that is, directly using a constant as a subscript), but it is implicit (that is, using a variable to represent the subscript) an error occurs frequently when a call is made. In another case, the length of the array defined in the program is determined by some specific methods rather than stated in advance. At this time, check the length of the array to avoid this exception. 5. java. lang. the exception of IllegalArgumentException is interpreted as "method parameter error", such as g. setColor (int red, int green, int blue) three values in this method, if there is more than 255, this exception will also occur, so once this exception is found, what we need to do, check whether the parameter passing in the method call is incorrect. 6. java. lang. the exception of IllegalAccessException is interpreted as "no access permission". This exception occurs when the application calls a class but the current method does not have access permission for this class. Pay attention to this exception when Package is used in the program.

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.