Java- abnormal Throwable, Exception, Error relations

Java- abnormal Throwable, Exception, Error - 243573295 - blog Park
https://www.cnblogs.com/hwaggLee/p/4509038.html

 

 

Java-异常Throwable,Exception,Error

 

 

 

   It refers to a variety of abnormal conditions the unexpected, such as: file not found, the network connection fails, illegal parameters.

  Exception is an event that occurs during the program run, interferes with the normal flow of instructions.

  By the Java API Throwable various abnormal numerous subclass of the class described. Accordingly, the Java exception is an object, an instance of a subclass of Throwable , error condition described in the paragraph coding. When the condition is generated, the error will be thrown.

 

In Java, all exceptions have a common ancestor Throwable (throwable). Throwable specify the code available in any common problems anomalous propagation mechanism of transmission through Java applications.

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

 

  Error (error): wrong program can not handle, indicate more serious problems running the application .

  Most errors unrelated to the operation and execution of code writers, and that the problem code is running JVM (Java Virtual Machine) appears. For example, Java virtual machine runtime error (Virtual MachineError), when the JVM is no longer required memory resources to continue operations, OutOfMemoryError will appear.

  When these exceptions occur, Java Virtual Machine (JVM) will generally choose to terminate a thread. These errors indicate a failure in its own virtual machine, or VM occurs when trying to execute applications such as Java Virtual Machine runtime error (Virtual MachineError), the class definition error (NoClassDefFoundError) and so on.

  These errors are not checked because they are outside the control and processing power of the application, but the vast majority are not allowed in the program is running situation. For application design and reasonable, even if an error does occur, in essence, we should not try to deal with the abnormal situation caused by it. In Java, the error described by the subclasses of Error.

       Exception (abnormal): abnormal program itself can handle.

       Exception class has an important subclass of RuntimeException. RuntimeException and its subclasses indicates an error caused by "JVM common operations." For example, when trying to use a null object reference, division by zero or array bounds, respectively, an exception is thrown (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException runtime.

    Note: the difference between exceptions and errors: the program itself may be an exception handling, error handling is not.

 

 

    Typically, Java exceptions (including Exception and Error) into abnormal to be investigated (checked exceptions) and not check the abnormality (an unchecked Exceptions) .

   Can be checked exception (the compiler requires an exception must be disposed of):, reason can accommodate abnormal conditions the correct procedures in the operation, it is easy to arise. Although it is to be investigated abnormal abnormal situation, but to some extent it occurs as can be expected, and once this abnormal situation occurs, we must take some manner for processing.

      In addition to its subclasses RuntimeException other Exception class and its subclasses are checked exception belong to. This unusual feature is the Java compiler will check it, that is to say, such an exception may occur when the program or capture it with the try-catch statement, either with a throws clause declared throws it, otherwise the compiler will not pass .

     Not check exception (the compiler does not require unusual disposal mandatory): Exception (a RuntimeException its subclasses) and error (Error) comprises a runtime.

 

 

     This anomaly Exception divided into two categories abnormal and non-runtime exception (the compiler abnormal) runtime . Program should be to deal with these exceptions as possible.

  Runtime exceptions: all abnormalities RuntimeException class and its subclasses, such as a NullPointerException (null pointer exception), an IndexOutOfBoundsException (subscript bounds exception), these abnormalities are not checked exception, capturing processing program may be selected, or may not handle. These abnormalities are generally caused by the program logic errors, the program should avoid such abnormal logically possible.

      Runtime exception is characterized by a Java compiler does not check it, that is to say, such an exception may occur when the program even without a try-catch statement catches it, throws clause declared useless throw it, will compile.
       Abnormality (abnormality compilation) Non-operating: is Exception belong to the class and its subclasses other than a RuntimeException type. From a linguistic point of view the program is an exception must be handled, if not addressed, the program will not compile. As IOException, SQLException Exception and other user-defined exception, no custom abnormalities in general.

 

 

Exception handling mechanism

     In Java applications, exception handling mechanism: throw exceptions, catch exceptions.

    Throws an exception : When a method throws an exception error occurs, the exception object methods to create and deliver the system is running, the exception object contains the exception type and program status at the time of abnormal abnormal information. The runtime system is responsible for finding and disposal of abnormal code execution. throws , the throw

        Catch exceptions : after method throws an exception, the runtime system will be converted to find suitable exception handler (exception handler). Potential exception handler is in turn retained collection method in the call stack when an exception occurs. When a match type of abnormality and method of abnormality type of exception thrown processor can handle, i.e. the appropriate exception handler. The system starts to run from the abnormal method, the method call stack in order to check back until the method containing the appropriate exception handler to find and execute. When operating the system walks the call stack without finding an appropriate exception handler, the runtime system is terminated. At the same time, the termination means that Java programs. try..catch

        For runtime exceptions, errors or checked exception, exception handling Java technology required is different.

        Due to abnormal runtime exceptions can not check resistance, in order to more rational and easier to implement applications, Java requirements, the system automatically thrown by the Java runtime runtime allows applications to run ignored.

       Error may occur in the method of operation, when the method of operation do not want to catch, Java allows the process to be thrown without any declaration. Because, most of the Error An exception is the situation never be allowed to happen, it is reasonable application should not catch exceptions.

       For all the anomalies to be investigated, Java provides: a method must catch, or throw statement outside the method. That is, when a method may choose not to catch a checked exception, you must declare it will throw an exception.

        The method can be captured exception, the exception handler matches the need to provide a type. Captured anomalies may be due to their own statements and throw exceptions caused, it could be run by a certain method or the Java runtime system throws an exception. In other words, a method can catch exceptions, it must be somewhere in the Java code exceptions thrown. Simply put, the exception is always the first to be thrown, after being captured.

         Any Java code can throw an exception, such as: I have written the code, from Java development environment package code, or Java runtime system. Whoever can be thrown by the Java throw statement.

        Thrown from the method throws any exception must use clause.

        Capture implement exceptions by try-catch statement or try-catch-finally statement.

         Overall, Java provides that: exceptions must be investigated for the capture, or throw statement. Not be allowed to ignore investigation RuntimeException and Error.

 

Catch the exception: try, catch and finally

Copy the code

try {  
    Program code // exception may occur  
} catch (Type1 id1){  
    // try to capture and dispose of the type of exception thrown Type1  
}  
catch (Type2 id2){  
     // try to capture and dispose of the thrown exception type Type2  
}  

Copy the code

   A pair of rear braces keyword will try an abnormal code may wrap area called monitoring. Java method exception occurs during operation, the exception object is created. The exception is thrown outside the surveillance zone by the Java runtime system attempts to find a matching catch clause to catch the exception. If a matching catch clause, the exception handling code to run it, try-catch statement ends.

       In the matching process: If the exception object is thrown exception class belonging catch clause, or belonging to subclass of this class exception, the exception that the type of the exception object generated catch block catches match.

 

Example 1  

Copy the code

public class TestException {  
    public static void main (String [] args) throws Exception {// throws by throwing an exception (represented by open if no other exception is received)
        int a = 6;  
        int b = 0;  
        try {// try monitored area  
            if (b == 0) throw new ArithmeticException (); // thrown by the throw statement  
            System.out.println ( "value of a / b is:" + a / b);  
        }  
        catch (ArithmeticException e) {// catch to catch exceptions  
            System.out.println ( "abnormal program appears, variable b can not be 0.");  
        }  
        System.out.println ( "the program ends normally.");  
    }  
}  

Copy the code

 

 

operation result:

Abnormal program appeared, the variable b can not be zero.
The program ends normally.

     It should be noted that once a catch Exception caught the type of match will enter exception handling code. Once processing is finished, it means that the whole try-catch statement ends. Other catch clause no longer have the opportunity to match and catch the exception types.

    Described by Java exception class exception type, exception class hierarchy shown in Figure 1. For a plurality of exception programs catch clause, we should try to capture the catch clause exception class bottom on the front, and try to capture the opposing catch top on the back clause exception classes. Otherwise, capture the underlying exception class catch clause will likely be shielded.

      RuntimeException exception class includes a variety of common abnormalities, ArithmeticException class ArrayIndexOutOfBoundsException class and its subclasses are running. Therefore, catch RuntimeException exception classes clause should be placed in the back, or you might disable subsequent specific exception handling or compile-time error.

 

 

throws an exception is thrown

   If a method may appear abnormal, but no ability to deal with this anomaly, you can use throws clause to declare an exception is thrown in the method declaration. Such as automobile may occur at run-time failures, the car itself is no way to deal with this fault, it would allow people to drive to deal with.

     throws statement is used in the method definition types of exceptions declared to be thrown by this method, if the exception type Exception is thrown, the method is declared to throw all exceptions. A plurality of abnormality may be separated by commas. Throws statement syntax is:

methodname throws Exception1,Exception2,..,ExceptionN  
{  
}

 throws Exception1 after the method name, Exception2, ..., the list of exceptions ExceptionN is declared to be thrown. When a method throws an exception exception list, the method is wrong with these types and their subclasses for the type of exception handling, and thrown to invoke the method method, charged with this matter processing.

 

 

Throws throws an exception of the rule:

    1) If it is not checked exception (unchecked exception), ie Error, RuntimeException or a subclass, you can not use the throws keyword to declare an exception to be thrown, the compiler can still pass, but in the run-time system will be thrown.

    2) must declare the method can throw any checked exception (checked exception). That is, if a method may appear to be investigated by an exception, either captured by try-catch statement, either with a throws clause declared throw it, otherwise it will cause a compiler error

    3) only if an exception is thrown, the caller of the method or process it must re-throw the exception. When the caller of the method of inability to handle the exception, it should continue to throw, rather than gulping.

 

    4) call processing method must follow any rules and declarations can be found exception. If override a method, you can not declare an exception and cover different methods. Any kind or a subclass must be declared to be abnormal overridden method declaration.

 

 

 

Use throw an exception is thrown

   throw always appear in the body of the function, used to throw an exception of type Throwable. After the program is terminated immediately throw statement, it is not behind the statement is executed, then it contains all the try block (upper layer may function call) from the try block contained in search its matching catch clause outwardly.
  We know that an exception is an instance of an object exception class, we can create an instance of the exception class by throw statement. The syntax of the statement is:

    throw new exceptionname;

 


    IOException thrown objects such as a class:

    throw new IOException;

 


    It is noted that, throw thrown can be thrown only instance of an object class or a subclass of Throwable. The following operation is wrong:

    throw new String("exception");

 

    This is not because the sub-class String Throwable class.

     If an exception is thrown checked exception type, it should also declare the method will throw the head. The caller of the method must also check processing throw.

       If all else layers of the abnormal throwing acquired JVM will eventually be processed, the processing is also very simple, is to print the exception message and stack information. If the Error is thrown or RuntimeException, the caller can select the method to handle the exception.

 

 

 

Throwable class common method

Note: catch keywords in brackets after the parameter type Exception e. Exception try block is passed to the catch block of variable types, e is the variable name. The catch block statement "e.getMessage ();" for outputting the nature of the error. Exception handling is usually used three functions to get information about the exception:

     getCause (): Returns the reason why thrown. If the cause is nonexistent or unknown, null is returned.

  getMeage (): returns an exception message information.

  printStackTrace (): target stack trace error output stream, the value of the field System.err.

     Sometimes in order to simply ignore the code will catch phrase, so try-catch statement has become a kind of decoration, once the program appeared abnormal during operation, handling exceptions will be ignored, and why the error occurred is hard to find.

 

 

 

Abnormal chain

 1) If the call quotient (3, -1), the MyException exception, the program transfer to catch (MyException e) occurs execution code block;

      2) If you call quotient (5,0), will be due to "divide by zero" error caused ArithmeticException abnormalities, abnormal belong to class when running, the system automatically thrown by the Java runtime. quotient () method does not catch ArithmeticException abnormal, Java runtime system caller of the method call stack method found along the main method, the thrown exception uploaded to the quotient ():

         int result = quotient (a, b ); // call the method Quotient ()
        Since the try statement in the monitored area, thus returned "division by zero" in ArithmeticException system exception is thrown by the Java runtime, catch and the sub-matching sentence:

       catch (ArithmeticException e) {// handle an ArithmeticException
System.out.println ( "divisor is not 0"); // output message

        The processing result, the output "divisor can not be 0." Java exception handling mechanism that is passed up information, formation of abnormal chain .

       Java method can throw a checked exception will be based on the call stack, call the hierarchy of methods have been passed along to the calling method of processing power, the highest level so far the main method. If the exception is passed to the main method, while the main do not have the processing power, the exception, compile errors will occur nor thrown through the throws statement.

 

      3) The other exception occurs, the use catch (Exception e) to catch exceptions. Because all exceptions Exception class is the parent class, if the catch (Exception e) block in front of the other two blocks of code, followed by the code block will never be executed, it does not make sense, so catch statement the order can not be swapped.

 

 

 

 

 

 

 

 

 

 

 

 

Common exceptions Java

Provides some frequently used to describe the error exception in Java, capture process for these exceptions, and some require the programmer to declare or thrown, some capture handled automatically by the Java Virtual Machine. Java common exception classes:

 

1. runtimeException子类:

     1, java.lang.ArrayIndexOutOfBoundsException
    array index out of bounds exception. When thrown array index value is negative it is equal to or greater than the array size.
    2, java.lang.ArithmeticException
    abnormal arithmetic conditions. For example: integer divide by zero and so on.
    3, java.lang.NullPointerException
    null pointer exception. When an application attempts to use a null object at the required place, Thrown. For example: Example of a null object method invocation, property access null object, calculating the length of a null object, null, etc. using throw statement
    4, java.lang.ClassNotFoundException
    class can not find abnormalities. When an application attempts according to a string of the class name of the class, and after traversing CLASSPAH not find the corresponding name of the class file, Thrown.

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

   6, java.lang.ArrayStoreException array contains incompatible Throws exception

   7, java.lang.SecurityException security exception

   8, java.lang.IllegalArgumentException illegal parameter error

2.IOException

IOException: abnormal operation of the input stream and output may occur when the flow.

EOFException file ends abnormally

FileNotFoundException File not found abnormalities

3. Other

ClassCastException type conversion exception class

ArrayStoreException array contains incompatible Throws exception

Database operation exception class SQLException

NoSuchFieldException field is not abnormal to find

NoSuchMethodException method does not throw exceptions found

NumberFormatException string into a number exceptions thrown

StringIndexOutOfBoundsException String index out of range exception thrown

IllegalAccessException not allow access to certain types of abnormal

When InstantiationException when an application tries to create an instance of a class using the Class class newInstance () method, but the specified class object can not be instantiated Thrown

 

 

Custom exception

 

Use the built-in Java exception classes can be described most unusual circumstances occur during programming. In addition, users can also customize exception. User-defined exception class, just inherit Exception class can be.
    Using the procedure custom exception class can be roughly divided into the following steps.
(1) Create a custom exception class.
(2) an object thrown by a throw keyword in the method.
(3) If the current processing method throws an exception of exceptions, you can use try-catch statement capture and processing; otherwise throws by keyword specifies the method to be thrown to the caller of an exception in the statement of the method, continue to the next step operating.
(4) capture and handle exceptions in the caller unusual method.

In the above "Use throw thrown" examples have been mentioned.

Guess you like

Origin blog.csdn.net/guyue35/article/details/90511739