exception refers to the various conditions, such as: file cannot be found, network connection failure, illegal parameters and so on.
An exception is an event that interferes with the normal instruction flow during the program's run.
Java describes various kinds of exceptions through the many subclasses of the Throwable class in the API. Thus,Java exceptions are objects, examples of throwable subclasses , and describe error conditions that occur in a piece of code. An error throws an exception when the condition is generated.
In Java, all exceptions have a common ancestor throwable (can be thrown). Throwable specifies the commonality of any problem that can be transmitted through a Java application using the exception propagation mechanism in the code.
Throwable: There are two important subclasses:Exception (Exception) and error (Errors), both of which are important subclasses of Java exception handling, each of which contains a large number of subclasses.
Error (Error): A bug that the program cannot handle, indicating a more serious problem in running the application .
Most errors are unrelated to what the code writer does, and represent a problem with the JVM (the Java virtual machine) that is running the code. For example, the Java Virtual machine runs the error (virtual Machineerror) and OutOfMemoryError occurs when the JVM no longer has the memory resources required to continue the operation.
When these exceptions occur, the Java Virtual machine (JVM) typically chooses to terminate the thread. These errors indicate that the failure occurred on the virtual machine itself, or when the virtual machine attempted to execute the application, such as a Java Virtual machine run error (virtual Machineerror), a class definition error (NOCLASSDEFFOUNDERROR), and so on.
These errors are not available because they are outside the control and processing power of the application and are mostly not allowed when the program is running. For a well-designed application, even if it does, it should not be an attempt to deal with the anomalies that it causes. In Java, errors are described by the subclasses of the error.
Exception (Exception): is an exception that the program itself can handle.
The Exception class has an important subclass runtimeexception. The RuntimeException class and its subclasses represent errors thrown by the JVM common Operation . For example, if you attempt to use null object references, divide by zero, or array out of bounds, the run-time exceptions (NullPointerException, ArithmeticException), and arrayindexoutofboundexception are raised respectively.
Note: Exceptions and errors are different: Exceptions can be handled by the program itself, and errors cannot be handled.
In general, Java exceptions (including exception and error) are categorized as checked exceptions and non-checked exceptions (unchecked exceptions).
can check exceptions (compiler requirements must be disposed of exceptions): the correct program in operation, it is easy to appear, reasonable tolerance of abnormal conditions. Although the abnormal condition can be checked, it can be predicted to some extent, and in the event of such abnormal situation, it must be handled in some way.
In addition to RuntimeException and its subclasses, other exception classes and their subclasses belong to the exception-checking. This exception is characterized by the Java compiler checking it, that is, when such an exception can occur in a program, either by capturing it with a try-catch statement or by declaring it with a throws clause, or the compilation will not pass.
Exception not checked (compiler does not require forced disposition of exceptions): Includes run-time exceptions (RuntimeException with its subclasses) and errors (error).
Exception This anomaly is divided into two major categories Run-time exceptions and non-run-time exceptions (compilation exceptions). These exceptions should be handled as much as possible in the program.
Run-time Exceptions: both the RuntimeException class and its subclass exceptions, such as nullpointerexception (null pointer exception), indexoutofboundsexception (subscript out-of-bounds exception), etc. These exceptions are not checked for exceptions, the program can choose to capture the processing, or it can not be processed. These exceptions are usually caused by a program logic error, and the program should avoid this kind of exception as much as possible from a logical point of view.
A run-time exception is characterized by the Java compiler not checking it, that is, when such an exception can occur in a program, even if it is not captured with the Try-catch statement, it is not thrown with the throws clause declaration, and it is compiled.
Non-runtime exception (compile exception): is an exception other than RuntimeException, and the type belongs to the exception class and its subclasses. From the point of view of the program syntax is the exception that must be handled, and if not handled, the program cannot be compiled through. such as IOException, SqlException, and user-defined exception exceptions, generally do not customize check exceptions.
Handling Exception mechanisms
In a Java application, the exception handling mechanism is: throw an exception, catch an exception.
Throw exception : When a method throws an exception with an error, the method creates the exception object and delivers the runtime system, which contains exception information such as the type of exception and the state of the program when the exception occurred. The runtime system is responsible for finding and executing the code that handles the exception. throws,throw
catch Exception : After the method throws an exception, the runtime system will look for the appropriate exception handler (exception handler). A potential exception handler is a collection of methods that persist in the call stack, in turn, when an exception occurs. An appropriate exception handler is the exception type that can be handled by the exceptions handler when it matches the type of exception thrown by the method. The runtime system starts with the method in which the exception occurred and then turns back to the method in the call stack until it finds the method that contains the appropriate exception handler and executes it. The runtime system terminates when the runtime system traverses the call stack without finding an appropriate exception handler. At the same time, it means the termination of the Java program. Try: Catch
Java technology requires different exception handling for run-time exceptions, errors, or exceptions that can be checked.
Because of the non-availability of runtime exceptions, in order to make the application more reasonable and easier to implement, Java rules that runtime exceptions are automatically thrown by the Java runtime system, allowing applications to ignore runtime exceptions.
Java allows the method to not make any throw declarations when the run method does not want to catch the error that may occur in the method's run. Because most error exceptions belong to a condition that can never be allowed to occur, it is also a reasonable exception that the application should not catch.
For all the exceptions that can be checked, the Java rule is that a method must catch, or declare the throw method. That is, when a method chooses not to catch an exception, it must declare that it will throw an exception.
The ability to catch exceptions requires a matching type of exception handler. The exception that is caught may be an exception that is thrown by an individual statement, or an exception that is thrown by a method called or by the Java Runtime System. In other words, the exception that a method can catch must be the exception that Java code throws on the premises. Simply put, the exception is always first thrown and then captured.
Any Java code can throw exceptions, such as code written by itself, code from the Java Development environment package, or a Java runtime system. No matter who, you can throw an exception through the Java throw statement.
Any exceptions that are thrown from a method must use the throws clause.
Catch exceptions are implemented through TRY-CATCH statements or try-catch-finally statements.
Overall, Java rules: You must catch, or declare, the exception to be checked. Allow RuntimeException and error to be ignored.
Catching exceptions: try, catch, and finally
try {
// Program code where exceptions may occur
} catch (Type1 id1) {
// Catch and handle the exception type Type1 thrown by try
}
catch (Type2 id2) {
// Catch and handle the exception type Type2 thrown by try
}
A pair of curly braces after the keyword try will wrap a piece of code that may have an exception, called the monitoring area. An exception object is created when the Java method has an exception during the run. The exception is thrown outside the monitoring area by the Java Runtime system trying to find a matching catch clause to catch the exception. If there is a matching catch clause, its exception-handling code is run, and the Try-catch statement ends.
The principle of matching is that if the thrown exception object belongs to the exception class of the Catch clause, or to the subclass of the exception class, the generated exception object is considered to match the type of exception caught by the catch block.
Example 1
public class TestException {
public static void main (String [] args) throws Exception {// throws an exception through throws (indicates that it is turned on if no other exception is received)
int a = 6;
int b = 0;
try {// try monitoring area
if (b == 0) throw new ArithmeticException (); // throw exception via throw statement
System.out.println ("The value of a / b is:" + a / b);
}
catch (ArithmeticException e) {// catch
System.out.println ("The program encountered an exception. The variable b cannot be 0.");
}
System.out.println ("The program ends normally.");
}
}
Operation Result:
The program has an exception and the variable B cannot be 0. The program ends normally.
It is important to note that once a catch catches a matching exception type, it enters the exception handling code. Once the processing is finished, it means that the entire Try-catch statement ends. Other catch clauses no longer have an opportunity to match and catch exception types.
Java describes the exception type through the exception class, which is shown in hierarchy 1 of the exception class. For an exception program with multiple catch clauses, you should try to put the catch clause that captures the underlying exception class in front of you as much as possible, and keep the catch clause of the exception class that captures the relative high level. Otherwise, the catch clause that captures the underlying exception class may be masked.
The runtimeexception exception class includes various common exceptions at run time, and the ArithmeticException class and ArrayIndexOutOfBoundsException class are subclasses of it. Therefore, the catch clause of the RuntimeException exception class should be placed on the last side, or it might mask the subsequent specific exception handling or cause a compilation error.
Throws throws an exception
If an exception is possible for a method, but is not capable of handling the exception, you can declare the throw exception by using the throws clause at the method declaration. For example, a car may fail when it is running, and the car itself cannot handle the failure, so let the driver handle it.
The throws statement declares the type of exception to be thrown by the method when the method is defined, and if it throws a exception exception type, the method is declared to throw all exceptions. Multiple exceptions can be separated using commas. The syntax format for the throws statement is:
throws exception1,exception2,.., exceptionn { }
The throws Exception1,exception2 after the method name is,..., exceptionn to declare the list of exceptions to be thrown. When the method throws an exception to the exception list, the method does not handle exceptions for those types and their subclass types, and throws the method that invokes the method, which is handled by him.
Throws throws an exception to the rule:
1) If the exception is not checked (unchecked exception), that is, error, runtimeexception, or their subclasses, you can declare the exception to be thrown without using the throws keyword, the compilation will still pass smoothly, but will be thrown by the system at runtime.
2) You must declare any checked that the method can throw (exception). That is, if a method may appear to be subject to a try-catch, either by the use of a statement, or by a throws clause declaration to throw it, or cause a compilation error
3) only if an exception is thrown, the caller of the method must handle or re-throw the exception. When the caller of the method is unable to handle the exception, it should continue to be thrown, rather than swallowed.
4) The calling method must follow any processing and declaration rules that can be checked for exceptions. If you override a method, you cannot declare an exception that differs from the overriding method. Any exception declared must be the same class or subclass of the exception declared by the overridden method.
Throw an exception with throw
The throw always appears in the function body and is used to throw an exception of type Throwable. The program terminates immediately after the throw statement, and the statement following it is not executed, and then in all the try blocks that contain it (possibly in the upper call function), look for the try block containing the catch clause that matches it.
We know that an exception is an instance object of an exception class, and we can create an instance object of the exception class thrown through a throw statement. The syntax format for this statement is:
Throw new Exceptionname;
For example, throw an exception object of the IOException class:
Throw New IOException;
It is important to note that throw throws only an instance object that can throw a class throwable or its subclasses. The following actions are incorrect:
Throw New String ("exception");
This is because string is not a subclass of the Throwable class.
If you throw a check exception, you should also declare the type of exception that the method might throw on the method header. The caller of the method must also check the exception that is thrown by the handle.
If all of the methods are thrown at layers, the JVM will eventually be processed and the processing is simple, which is to print the exception message and stack information. If an error or runtimeexception is thrown, the caller of the method can choose to handle the exception.
Common methods in the Throwable class
Note the parameter E of the exception type in parentheses after the catch keyword. Exception is the variable type that the try code block passes to the catch code block, and E is the variable name. The statement "E.getmessage () in the catch code block;" Used for output error properties. Typically, exception handling uses 3 functions to get information about the exception:
Getcause (): Returns the reason that the exception was thrown. If cause does not exist or is unknown, NULL is returned.
Getmeage (): Returns the message information for the exception.
Printstacktrace (): The stack trace of the object is output to the error output stream as the value of the field System.err.
Sometimes in order to simply ignore the catch statement after the code, so that the Try-catch statement becomes a device, once the program in the process of running an exception, it will ignore the handling of the exception, and the cause of the error is difficult to find.
Exception chain
1) if quotient (3,-1) is called, a myexception exception occurs and the program is reversed to catch (MyException e) code block execution;
2) If you call quotient (5,0), the ArithmeticException exception will be thrown due to a "divisor of 0" error, which belongs to the runtime exception class and is automatically thrown by the Java runtime System. The quotient () method does not catch the ArithmeticException exception, and the Java Runtime system will follow the method call stack to the main method, uploading the thrown exception to the caller of the quotient () method:
int result = Quotient (a, b); Call Method Quotient ()
Because the statement is within the try monitoring area, the ArithmeticException exception returned by the "divisor is 0" is thrown by the Java runtime system and matches the catch clause:
catch (ArithmeticException e) {//Handle ArithmeticException exception
SYSTEM.OUT.PRINTLN ("Divisor cannot be 0"); Output hint information
}
The result of the processing is the output "divisor cannot be 0". Java, the processing mechanism of the upward passing of exception information, forms an anomaly chain .
A readable exception thrown by a Java method is passed to the calling method with the ability to process, at the highest level, to the main method, based on the call stack and the hierarchy along the method invocation. If the exception is passed to the main method, and main does not have the processing power, and the exception is not thrown through the throws declaration, a compilation error may occur.
3) If there are other exceptions, the catch (Exception e) will be used to catch the exception. Because Exception is the parent class of all exception classes, if you put catch (Exception e) blocks of code in front of the other two blocks of code, the subsequent code blocks will never be executed, which makes no sense, so the order of the catch statements is not swap.
Common Java Exceptions
Some exceptions are provided in Java to describe frequently occurring errors, some of which require a programmer to capture or declare, and some are automatically captured by a Java virtual machine. Common exception classes in Java:
1. RuntimeException Sub-category:
1, 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.
2, Java.lang.ArithmeticException
Arithmetic condition exception. For example: integers except 0.
3, Java.lang.NullPointerException
Null pointer exception. This exception is thrown when an app tries to use null where the object is required. Example: Invoking an instance method of a null object, accessing the properties of a null object, calculating the length of a null object, throwing null with a throw statement, and so on
4, Java.lang.ClassNotFoundException
The class exception could not be 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.
5, java.lang.NegativeArraySizeException array length is negative exception
6. Exceptions thrown by incompatible values in the Java.lang.ArrayStoreException array
7. Java.lang.SecurityException Security exception
8. Java.lang.IllegalArgumentException Illegal parameter exception
2.
IOException
IOException: An exception that may occur when manipulating input and output streams.
Eofexception file has ended exception
FileNotFoundException File not found exception
3. Other
ClassCastException type Conversion Exception class
Arraystoreexception an exception that is thrown in an array that contains incompatible values
SQLException Manipulating Database Exception classes
nosuchfieldexception Field not found exception
The Nosuchmethodexception method did not find the thrown exception
NumberFormatException string conversion to a number thrown exception
Stringindexoutofboundsexception string index out of range throw exception
Illegalaccessexception does not allow access to a class of exceptions
Instantiationexception when an application attempts to create an instance of a class using the Newinstance () method in the class classes, and the specified class object cannot be instantiated, the exception is thrown
Custom exceptions
Use the Java built-in exception class to describe most of the exceptions that occur during programming. In addition, users can customize exceptions. User-defined exception class, just inherit the exception class.
The use of custom exception classes in your program can be broadly divided into the following steps.
(1) Create a custom exception class.
(2) throws the exception object through the Throw keyword in the method.
(3) If the exception is handled in the method that currently throws the exception, it can be captured and processed using the Try-catch statement, otherwise the exception that is thrown to the method caller is indicated by the throws keyword at the declaration of the method, and proceed to the next step.
(4) Catch and handle exceptions in the caller of the exception method.
The "throw exception using throw" example above is already mentioned.
java-Abnormal Throwable,exception,error