Common Android Exceptions

Source: Internet
Author: User

1. Exception mechanism
1.1 exception mechanism refers to how the program handles when a program error occurs. Specifically, the exception mechanism provides a secure channel for program exits. 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 way of handling exceptions is that the function returns a special result to indicate an exception (usually this particular result is commonly called), and the program that invokes the function is responsible for examining and parsing the results returned by the function. This is a disadvantage: for example, the function return-1 represents an exception, but if the function does want to return 1 the correct value of the confusion, the readability is reduced, the program code and the code to deal with the exception of the father together, the call function of the program to parse the error, which requires the client programmer has 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 in it
2 Classification of exceptions
2.1 Classification of exceptions
inheritance structure for 2.1.1 Exceptions: base classes inherit ioexception such as Throwable,error and exception inheritance throwable,runtimeexception and exception, The concrete runtimeexception inherits the RuntimeException.
2.1.2 Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).
2.2 Characteristics of each type of anomaly
The error class system of the 2.2.1 error system describes the internal errors and resource exhaustion scenarios in the Java operating system. Applications should not throw objects of this type (typically thrown by virtual machines). In the event of such an error, there is nothing else to do except to try to get the program safely out of the way. Therefore, in the program design, should pay more attention to the exception system.
the exception system of 2.2.2 Exception system includes RuntimeException system and other non-runtimeexception system.
the 2.2.2.1 runtimeexception runtimeexception system includes wrong type conversions, array cross-border access, and attempts to access null pointers, and so on. The principle of dealing with runtimeexception is that if a runtimeexception occurs, it must be a programmer's fault. For example, you can avoid array out-of-bounds access exceptions by examining array subscripts and arrays boundaries.
2.2.2.2 Other (IOException, etc.) such exceptions are generally external errors, such as trying to read data from the end of a file, which is not an error in the program itself, but an external error that occurs in the application environment.
2.3 Differences from C + + exception classifications
2.3.1 In fact, the runtimeexception of this class name in Java is inappropriate because any exception is present at runtime. (Errors that occur at compile time are not exceptions, in other words, exceptions are to resolve errors that occur when the program runs).
in 2.3.2 C + +, Logic_error is equivalent to RuntimeException in Java, and Runtime_error is equivalent to an exception in Java that is not runtimeexception type.
3 How to use exceptions
3.1 Declaring a method throws an exception
3.1.1 Syntax: throws (slightly)
3.1.2 Why declare a method to throw an exception? Method throws an exception 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 the code that handles the exception. Then, in the event of an exception, there is no suitable exception controller to resolve the exception.
3.1.3 Why is the exception thrown must have been checked for exceptions? RuntimeException and error can be generated in any code, they do not need to be shown by the programmer to throw, and in the event of an error, the corresponding exception will be automatically thrown. Just checking that the exception was thrown by the programmer is in two cases: the client programmer calls the library function that throws the exception (the exception to the library function is thrown by the library programmer), and the client programmer throws an exception using the throw statement himself. When encountering error, programmers are generally powerless; when encountering runtimeexception, there must be a logic error in the program, 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 a parent class cannot throw more exceptions than the parent class method, so sometimes the method of the parent class is designed to declare an exception, but the code of the actual implementation method does not throw an exception, which is intended to make it easier for the subclass method to overwrite the parent class method.
3.2 How to throw an exception
3.2.1 Syntax: throw (slightly)
3.2.2 What exception is thrown? For an exception object, the really useful information is the exception object type, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, then the class name is the only useful information. So, when choosing what exception to throw, the key is to choose the class name of the exception that clearly describes the exception.
3.2.3 Exception objects typically have two constructors: one is a parameterless constructor, and the other is a constructor with a string that acts as an extra description of the 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 is important to note that the only useful information is the type name, so do not expend effort on the design of the exception class.
3.3 Catching an exception if an exception is not handled, the program is aborted and output exception information for a non-graphical program, and for a GUI program, the exception information is output, but the program does not abort, but instead returns to the user interface processing loop.
3.3.1 Syntax: The try, catch, and finally (slightly) Controller module must be immediately behind 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 that catch clause and considers the exception to be controlled. Once the catch clause ends, the search for the controller stops. 3.3.1.1 Capturing multiple exceptions (note syntax and order of capture) (slightly)
3.3.1.2 finally's usage and exception handling flow (slightly)
what does 3.3.2 do with exception handling? For Java, because of garbage collection, exception handling does not need to reclaim memory. But there are still some resources that need to be compiled by programmers, such as files, web connections, and pictures.
3.3.3 Should I declare a method to throw an exception or catch an exception in a method? Principle: Catching and dealing with exceptions that know how to handle them, and passing on those that do not know how to handle them
3.3.4 throws an exception again
3.3.4.1 Why do you want to throw an exception again? In this level, only a subset of the content can be processed, and some processing needs to be done in a higher level environment, so the exception should be thrown again. This allows each level of the exception handler to handle the exceptions it can handle.
3.3.4.2 exception handling process the catch block corresponding to the same try block will be ignored, and the thrown exception will go to a higher level.
4 Other questions about the exception
4.1 Overuse exceptions first, the use of exceptions is convenient, so programmers are generally no longer willing to write code handling errors, but simply throw an exception. This is not true, and for fully known errors, you should write code that handles this error, increasing the robustness of the program. In addition, the efficiency of the anomaly mechanism is poor.
4.2 Separating exceptions from normal errors for common, completely consistent errors, you should write code that handles this error and increase the robustness of the program. Exceptions are only required for externally indeterminate and predictable run-time errors.
4.3 information contained in an exception object 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 the exception string constructor. Calling the exception object's GetMessage (), toString (), or Printstacktrace () methods can get additional information about the exception object, the class name, and the call stack, respectively. And the latter contains a superset of the previous information.

Common Exceptions:

operations not supported by Unsupportedoperationexception

illegalargumentexception Illegal parameters

indexoutofboundsexception index out of bounds

illegalstateexception Illegal State
exceptions have a certain difference from common warnings. When an application exception occurs, it interrupts the normal instruction flow of the program being executed. That is, the code that follows the exception will not be executed correctly. The fallback operation of the database is even triggered.

In the Java development platform, exceptions include pre-defined exceptions and custom exceptions. The types of these two exceptions complement each other. As a qualified program developer, be good at using exceptions in your application. This can improve the interactivity of the application. At the same time, it is also the premise to ensure the normal operation. The exception handling is very important for developing an excellent application. For this reason, I think program developers should have an in-depth understanding of common exceptions to Java applications. The handling of custom exceptions can only be done if you understand these common exceptions.

the types and causes of common anomalies.

for the common exception of Java application, I think the program developer should understand 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 the program manager to pay attention to the accumulation in the daily work, but also needs to collect the data from other sources if necessary. The author of this is an analysis, I hope to be able to you program developers have some help.

1, SQLException: Operation Database Exception class.

most of today's Java applications depend on the database to run. This class is triggered when an error occurs when a Java application communicates with the database. The error information for the database is also displayed to the user through this class. In other words, this operation database exception class is the bridge between the database and the user exception information passing. As the user now inserts data into the system, the database specifies that a field must be unique. When the user inserts the data, if the value of this field is repeated with the existing record, violating the uniqueness constraint of the database, the database will run out an exception message. This information is generally not visible to users because it occurs at the database level. At this point the Operation database exception class will catch the exception information of the database, and pass this 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 operation database exception class. In a Java application, this class fires whenever an exception occurs for all database operations. All the hints in the Java application itself are often too general, only to say that there is an error in interacting with the database, and that there is not much reference value. At this point, the database is more useful than the prompt information.

2, ClassCastException: Data type conversion exception.

In Java applications, it is sometimes necessary to convert data types. This conversion includes the conversion of the display and the implicit conversion. However, no matter how the conversion, you must meet a precondition, that is, the compatibility of data types. If this principle is violated during the data conversion process, then the data type conversion exception is triggered. As now in the application, developers need to convert a character-type date data into date-based data that the database can accept, and only need to control it in the foreground application, generally without problems. However, if the foreground application lacks relevant controls, such as when the user enters the date with only the month, day information, and no year information. An exception occurs when the application is converting data types. According to the author's experience, the data type conversion exception is a relatively low-level exception in application development to make a more unusual occurrence. Because in most cases, you can have some enforcement 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 create a conversion exception for the data type. In fields where only numeric types are allowed, you can set characters that do not allow the user to enter values other than the value. Although there is an exception handling mechanism, you can guarantee that the application will not be run incorrectly. But in the actual development, it is to anticipate as much as possible the cause of the error, as far as possible to avoid the occurrence of anomalies.

3, NumberFormatException: The exception that is thrown when a string is converted to a numeric type.

In the process of data type conversion, if the problem occurs during the conversion of a character type to a digital type, a separate exception is used in the Java program for this exception, that is, numberformatexception. Data "123456", as now speaking of character type is allowed when converting to numeric data. However, if the character data contains non-numeric characters, such as 123#56, an exception occurs when converted to a numeric type. The system catches the exception and processes it.

There are many more common exception classes in Java applications. If the corresponding class exception is not found, some class exceptions are not allowed, the file has ended abnormally, the file does not find an exception, the field does not find an exception, and so on. General system developers can determine the type of the current exception based on the exception name. Although good, but better memory than bad writing. The program developer, when necessary (especially when there is a custom exception), has a list of exceptions at hand. In this case, whether the application in the debugging process to find the problem, or the process of running the user's complaints, can be timely according to the name of the exception to find the cause of the exception. This allows the exception to be resolved in the shortest possible time to restore the application's normal operation. This measure has been used by the author for many years and is very effective.

second, the exception management of practical advice.

Java applications provide only one exception class for manipulating database exceptions. Therefore, it is often not possible to help application personnel troubleshoot the cause of errors by relying on Java application error messages. This exception can only be named for an application error or a database error. To further identify the cause of the problem, it is best to explain the specific reasons when defining exceptions at the database level. For example, a foreground application might call a database function or procedure. At this point in the database function or process to be able to explain the specific reason for an exception. If you generate another table from one of the underlying tables, a field cannot be empty, and so on. When these exception information is explained clearly, if a similar exception is encountered, the operation database exception class will reverse the exception information of the database to the foreground user. This helps users to find the cause of the problem and correct it in the shortest time. Of course, this requires a Java programmer to coordinate with the Database Designer.

The second thing to note is that exceptions are not the norm. In other words, most anomalies can be eliminated by reasonable anticipation and prevention of the premises. If you design to arithmetic, you can limit the number of entries in the foreground application window, such as entering a value of 0, to eliminate any exceptions that may occur in the application's operation. However, this often requires the application developer to have more extensive work experience and more rigorous thinking logic. Although this has some difficulty, but I think the program developers should still work on this, rather than always let the user as your test, let the user to discover the design bug in the application. In my opinion, only some of the 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 such an exception from occurring.



ArithmeticException (Exception with divisor 0), bufferoverflowexception (overflow exception on buffer), bufferunderflowexception (buffer underflow exception), Indexoutofboundsexception (out-of-bounds exception), nullpointerexception (null pointer exception), Emptystackexception (empty stack exception), IllegalArgumentException (illegal parameter exception), Negativearraysizeexception, Nosuchelementexception, SecurityException, SystemException, Undeclaredthrowableexception

1. Java.lang.NullPointerException
The explanation of the exception is that "the program encounters a null pointer", which simply means that an uninitialized object or a nonexistent object is called, which confuses the initialization of the array with the initialization of the set element. The initialization of an array is the space required for the allocation of arrays, and the initialized array, where the elements are not instantiated, are still empty, so you also need to initialize each element (if it is to be called).
2. The java.lang.ClassNotFoundException exception is interpreted as "The specified class does not exist."
3. Java.lang.ArithmeticException this anomaly is interpreted as "a mathematical anomaly," such as an exception that occurs in a program divided by 0.
4. Java.lang.ArrayIndexOutOfBoundsException
The explanation of the exception is "array subscript out-of-bounds", now most of the program has an array of operations, so in the call arrays must be carefully checked, to see if the subscript is not beyond the scope of the array, in general, the display (that is, directly with the constant subscript) call is not easy to make such a mistake, But implicit (that is, the use of variable-subscript) calls are often wrong, there is also a case, the length of the array defined in the program is determined by certain methods, not in advance declaration, at this time, it is best to look at the length of the array to avoid this exception.
5. Java.lang.IllegalArgumentException
The explanation of this exception is "parameter error of the method", such as G.setcolor (int red,int green,int blue) Three values in this method, if more than 255 will also occur this exception, so once we find this anomaly, we have to do, Just go check it out. Parameter passing in the method call is not an error.
6. Java.lang.IllegalAccessException
This exception is interpreted as "no access", which occurs when the application is calling a class, but the current method does not have access to the class. Note This exception in cases where the package is used in the program


Common Android Exceptions

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.