1. Exception mechanism
The exception mechanism is what the program does when an 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.
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. Process of exception handling: ① encounters an error, the method ends immediately, does not return a value, and throws an exception object. ② The program that called 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
Classification of exceptions:
Inheritance structure for ① Exceptions: base classes inherit ioexception such as Throwable,error and exception inheritance throwable,runtimeexception and exception, The concrete runtimeexception inherits the RuntimeException.
②error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).
Characteristics of each type of exception
The error class 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 includes runtimeexception systems and other non-runtimeexception systems:
The ①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.
② Other non-runtimeexception (IOException, etc.): Such exceptions are generally external errors, such as attempting 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.
differs from C + + exception classification:
It is inappropriate to runtimeexception this class name in ①java because any exception is present at run time. (Errors that occur at compile time are not exceptions, in other words, exceptions are to resolve errors that occur when the program runs).
The Logic_error in ②c++ is equivalent to RuntimeException in Java, and Runtime_error is equivalent to the exception of non-runtimeexception types in Java.
3 How to use exceptions
Declaring a method throws an exception
① syntax: throws (slightly)
② 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.
③ 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.
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, and the purpose is to make it easier for the subclass method to overwrite the parent class method when the exception can be thrown.
How to throw an exception
① syntax: throw (slightly)
What exception does ② throw? 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.
③ 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.
④ 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.
If an exception is not handled, then, for a non-GUI program, the program will be aborted and output exception information, for a graphical interface program will also output the exception information, but the program does not abort, but return with the error page. Syntax: try, catch, and finally (slightly), the 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.
Capturing multiple exceptions (note syntax and order of capture) (slightly)
Finally usage and exception handling flow (slightly)
What does exception handling do? 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.
Should I declare a method to throw an exception or catch an exception in a method? Principle: Catch and handle exceptions that know how to handle them, and which ones do not know how to handle them.
Throw an exception again
① 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.
② Exception Handling Flow: the catch block corresponding to the same try block is ignored, and the thrown exception goes to a higher level.
4 Other questions about the exception
① excessive use of exceptions: first, it is 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, 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.
② separates exceptions from common errors: for common, completely consistent errors, code that handles this error should be written to increase the robustness of the program. Exceptions are only required for externally indeterminate and predictable run-time errors.
③ the information contained in the 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.
1. java.lang.nullpointerexception This exception everyone must often encounter, the abnormal explanation is "the program encountered a null pointer", simply called an uninitialized object or a nonexistent object, this error often appears in the creation of pictures, Call array in these operations, the slice is not initialized, or the picture is created with a path error, and so on. A null pointer appears in an array operation, and in many cases is a common mistake made by friends who are just beginning to learn programming, which confuses the initialization of arrays and the initialization of the array elements. 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. java.lang.classnotfoundexception This anomaly is a lot of programmers developed in the development environment, such as JB, put the package under the JB under WTK to compile the frequently occurring problem, the explanation of the exception is "The specified class does not exist", Here is the main consideration of the class name and path is correct, if the package is done under the JB, is usually the default plus packages, so go to the WTK to pay attention to the package path Add. 3. java.lang.arithmeticexception the explanation of this anomaly is "mathematical operation Anomaly", such as the program appears divided by 0 such an operation will be such an exception, for this anomaly, we will have to examine the program in their own procedures involving the mathematical operations of the place, The formula is not wrong. 4. java.lang.arrayindexoutofboundsexception This exception is believed many friends also often encountered, abnormal explanation is "array subscript out of bounds", now most of the program has an array of operations, Therefore, in the invocation of the array must be carefully checked to see if the subscript itself is beyond the range of the array, in general, the display (that is, directly with the constant subscript) call is not too easy to make such a mistake, but the implicit (that is, the use of variable representation subscript) calls are often wrong, there is a situation, The length of the array defined in the program is determined by certain methods and is not declared beforehand, so it is better to look at the length of the array before this exception occurs. 5. java.lang.illegalargumentexception This exception is interpreted as "parameter error of the method", and many of the methods in the J2ME class library can cause such errors in some cases, such as the volume adjustment methodIf the volume parameter is written as a negative number, this exception will occur, such as g.setcolor (int red,int green,int blue) Three values in this method, if there are more than 255 of this exception will occur, 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. Be aware of this exception in cases where the package is used in the program. Other There are a lot of anomalies, I will not list, I would like to explain that a qualified programmer, the program needs to have a good understanding of common problems and corresponding solutions, otherwise just stay in writing procedures and will not change the program, will greatly affect their own development. The full description of the exception is available in the API. Arithmetic exception class:arithmeticexecption null pointer exception class:nullpointerexception type cast exception:classcastexception Array negative subscript exception:negativearrayexception array subscript out of bounds exception:arrayindexoutofboundsexception violate security principle exception: Secturityexception file has ended exception:eofexception file was not found exception:filenotfoundexception string converted to a numeric exception:numberformatexception Operation database exception:sqlexception Input Output exception:ioexception method not found exception:nosuchmethodexception java.lang.abstractmethoderror Abstract method Error. Thrown when an application tries to invoke an abstract method. java.lang.AssertionError assertion is wrong. Used to indicate a condition in which an assertion failed. java.lang.ClassCircularityError cyclic dependency error. When a class is initialized, the exception is thrown if a circular dependency between the classes is detected. java.lang.classformaterror class format error. Thrown when a Java virtual machine attempts to read a Java class from a file and detects that the contents of the file do not conform to the valid format of the class. java.lang.Error error. is the base class for all errors that identify serious program run issues. These problems often describe anomalies that should not be captured by the application. java.lang.ExceptionInInitializerError Initialization program error. Thrown when an exception occurs during the execution of a static initializer for a class. Static initializers refer to static statement segments that are included directly in the class. java.lang.IllegalAccessError illegal access error. This exception is thrown when an application attempts to access, modify, or invoke the domain (field) of a class or call its methods, but violate the visibility declaration of a domain or method. java.lang.IncompatibleClassChangeError incompatible class change error. This exception is thrown when an incompatible change is made to the class definition on which the method being executed depends. This error is easily thrown when you modify the declaration definition for some classes in your app without recompiling the entire application. java.lang.InstantiationError instantiation errors. An . java.lang.internalerror internal error is thrown when an application attempts to construct an abstract class or interface through Java's new operator. Used to indicate an internal error occurred with the Java virtual machine. java.lang.LinkageError link error. The error and all its subclasses indicate that a class depends on another class, and after that class is compiled, the dependent class changes its class definition without recompiling all of the classes, which in turn raises the error condition. java.lang.NoClassDefFoundError class definition error not found. This error is thrown when a Java virtual machine or class loader attempts to instantiate a class and cannot find the definition of the class. There are no errors in the java.lang.NoSuchFieldError domain. This error is thrown when an application attempts to access or modify a domain of a class that does not have a definition of that domain in the definition of that class. The java.lang.NoSuchMethodError method has no errors. When an application attempts to invoke a method of a class that does not have the definition of theThe error is thrown when the method is defined. java.lang.OutOfMemoryError Insufficient memory error. This error is thrown when the available memory is insufficient for a Java virtual machine to be assigned to an object. java.lang.StackOverflowError Stack Overflow error. This error is thrown when the hierarchy of an application recursive call is too deep to cause a stack overflow. java.lang.ThreadDeath thread end. This error is thrown when the stop method of the thread class is called to indicate the end of the thread. java.lang.UnknownError unknown error. Used to indicate a situation in which a Java virtual machine has an unknown critical error. java.lang.UnsatisfiedLinkError an unsatisfied link error. Thrown when a Java virtual machine does not find a class that is declared as a native language definition of the native method. java.lang.UnsupportedClassVersionError Unsupported class version error. This error is thrown when the Java Virtual machine attempts to read a class file, but discovers that the primary and minor version number of the file is not supported by the current Java virtual machine. java.lang.VerifyError validation errors. This error is thrown when the validator detects an internal incompatibility or security issue in a class file. java.lang.VirtualMachineError Virtual machine error. A condition that indicates that the virtual machine is compromised or that the resource required to continue performing the operation is insufficient. java.lang.ArithmeticException arithmetic condition exception. For example: integers except 0. 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. java.lang.ArrayStoreException array Storage exception. Thrown when a non-array declaration type object is placed into the array. java.lang.ClassCastException styling anomalies. Assuming that there are classes A and B (A is not a parent or subclass of B), and O is an instance of a, the exception is thrown when an O is forced to be constructed as an instance of Class B. This exception is often called coercion type conversion exception. java.lang.classnotfoundexception The class exception was not 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. java.lang.CloneNotSupportedException cloning exceptions are not supported. When the Cloneable interface is not implemented or the Clone method is not supported, the exception is thrown by calling its clone () method. The java.lang.EnumConstantNotPresentException enumeration constant does not have an exception. This exception is thrown when an application attempts to access an enumeration object by name and enumeration type, but the enumeration object does not contain a constant. java.lang.Exception Root exception. Used to describe what the application wants to capture. java.lang.IllegalAccessException illegal access exception. This exception is thrown when an application attempts to create an instance of a class by reflection, accesses the class property, calls the class method, and then cannot access the definition of a class, property, method, or constructor method. java.lang.IllegalMonitorStateException violations of the monitoring State anomalies. This exception is thrown when a thread tries to wait for a monitor that does not own the object (O) or notifies other threads to wait for the object (O). java.lang.IllegalStateException abnormal state of law. This exception is thrown when the Java environment and the application are not already in the legal invocation state of a method, and the method is called. java.lang.IllegalThreadStateException illegal thread state exception. An exception is thrown when the county seat is not in the legal calling state of a method and the method is called. java.lang.IndexOutOfBoundsException index out of bounds exception. This exception is thrown when an index value that accesses a sequence is less than 0 or greater than or equal to the sequence size. java.lang.InstantiationException instantiation exception. This exception is thrown when an attempt is made to create an instance of a class through the newinstance () method, which is an abstract class or interface. java.lang.InterruptedException aborted exception. When a thread is waiting for a long time,Hibernation or other paused state, while the other thread throws the exception when it terminates the thread through the interrupt method of the thread. java.lang.NegativeArraySizeException array size is a negative value exception. This exception is thrown when an array is created with a negative size value. java.lang.NoSuchFieldException no exception exists for the attribute. This exception is thrown when a property that does not exist for a class is accessed. The java.lang.NoSuchMethodException method has no exception. This exception is thrown when a non-existent method of a class is accessed. java.lang.NullPointerException NULL pointer exception. This exception is thrown when an app tries to use null where the object is required. For example: Call an instance method of a Null object, access the properties of a null object, evaluate the length of a null object, throw null with a throw statement, and so on. java.lang.NumberFormatException number format exception. This exception is thrown when an attempt is made to convert a string to the specified number type, and the string does not satisfy the format required by the number type. java.lang.RuntimeException run-time exception. is the parent class of exceptions that can be thrown during normal operation of all Java virtual machines. java.lang.SecurityException security exceptions. Thrown by the security manager to indicate an exception that violates the security situation. java.lang.StringIndexOutOfBoundsException string index out of bounds exception. This exception is thrown when an index value is used to access a character in a string, and the index value is less than 0 or greater than or equal to the sequence size. There is no exception for the java.lang.TypeNotPresentException type.
Java exception mechanism