1. Introduction
try…catch… finally is probably a sentence that everyone is familiar with, and it feels very simple to use, and it seems logically easy to understand. However, the "learning" I experienced personally told me that this thing is not as simple and obedient as I imagined. Don't believe it? Then look at the code below, what will be the result after it is executed? Don't look at the answers backwards, nor do you allow code to be executed to see the real answers. If your answer is correct, then you don’t have to waste time reading this article.
package Test; public class TestException { public TestException() { } boolean testEx() throws Exception { boolean ret = true; try { ret = testEx1(); } catch (Exception e) { System.out.println("testEx, catch exception"); ret = false; throw e; } finally { System.out.println("testEx, finally; return value=" + ret); return ret; } } boolean testEx1() throws Exception { boolean ret = true; try { ret = testEx2(); if (!ret) { return false; } System.out.println("testEx1, at the end of try"); return ret; } catch (Exception e) { System.out.println("testEx1, catch exception"); ret = false; throw e; } finally { System.out.println("testEx1, finally; return value=" + ret); return ret; } } boolean testEx2() throws Exception { boolean ret = true; try { int b = 12; int c; for (int i = 2; i >= -2; i--) { c = b / i; System.out.println("i=" + i); } return true; } catch (Exception e) { System.out.println("testEx2, catch exception"); ret = false; throw e; } finally { System.out.println("testEx2, finally; return value=" + ret); return ret; } } public static void main(String[] args) { TestException testException1 = new TestException(); try { testException1.testEx(); } catch (Exception e) { e.printStackTrace(); } } } What is your answer? Is it the answer below?
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false
If your answer is really as mentioned above, then you are wrong. ^_^, then I suggest you read this article carefully or use the above code to modify, execute, and test according to various situations. You will find that there are many things that are not as simple as originally imagined. Now publish the correct answer:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false
Note:
Finally statement block should not appear, return should appear. The return ret above is preferably another statement to handle the relevant logic.
2. Java exception
Exceptions refer to various situations that occur unexpectedly, such as: file not found, network connection failure, illegal parameters, etc. An exception is an event that occurs during the program's run and interferes with the normal instruction flow. Java describes various exceptions through many subclasses of the Throwable class in the API. Therefore, Java exceptions are objects, instances of Throwable subclasses, describing error conditions that appear in a encoding. When a condition is generated, an error will throw an exception.
Java exception class hierarchy diagram:
Figure 1 Java exception class hierarchy diagram
In Java, all exceptions have a common ancestor, Throwable (throwable). Throwable specifies the commonality of any problems that can be transmitted through Java applications in the code by exception propagation mechanisms.
Throwable: There are two important subclasses: Exception and Error. Both are important subclasses for Java exception handling, and each contains a large number of subclasses.
Error: An error that the program cannot handle, indicating a serious problem in running the application. Most errors are not related to the actions performed by the code writer, but represent problems with the JVM (Java virtual machine) when the code is run. For example, a Java virtual machine runs an error (Virtual MachineError), and an OutOfMemoryError will appear when the JVM no longer has the memory resources needed to continue the operation. When these exceptions occur, the Java virtual machine (JVM) generally chooses to terminate threads.
These errors indicate that the failure occurs when the virtual machine itself, or when the virtual machine tries to execute the application, such as a Java virtual machine running error (Virtual MachineError), class definition error (NoClassDefFoundError), etc. These errors are undetectable because they are outside the control and processing capabilities of the application, and most of them are situations that are not allowed to occur when the program is running. For a well-designed application, even if an error does occur, it should not essentially try to deal with the exceptions it causes. In Java, the error is described by a subclass of Error.
Exception: An exception that the program itself can handle.
The Exception class has an important subclass, RuntimeException. The RuntimeException class and its subclasses represent an error raised by "Common JVM Operations". For example, if you try to use a null object reference, zero divisor or array out of bounds, a runtime exception (NullPointerException, ArithmeticException) and ArrayIndexOutOfBoundException are respectively raised.
Note: The difference between exceptions and errors: Exceptions can be handled by the program itself, but errors cannot be handled.
Generally, Java exceptions (including Exception and Error) are divided into checked exceptions and unchecked exceptions.
Exceptions can be checked (exceptions that must be handled by the compiler): It is easy to occur and reasonable and tolerant exceptions when the correct program is running. Although the checkable exception is an abnormal condition, its occurrence is predictable to a certain extent, and once such an abnormal condition occurs, it must be handled in some way.
Except for RuntimeException and its subclasses, other Exception classes and their subclasses are all checkable exceptions. The characteristic of this exception is that the Java compiler will check it, that is, when such an exception may occur in the program, either catch it with the try-catch statement or throw it with the throws clause, otherwise the compilation will not pass.
Uncheckable exceptions (exceptions that the compiler does not require forced disposal): including runtime exceptions (RuntimeException and its subclasses) and errors (Error).
Exception This exception is divided into two categories: runtime exception and non-runtime exception (compilation exception). These exceptions should be handled as much as possible in the program.
Runtime exceptions: they are all RuntimeException class and its subclass exceptions, such as NullPointerException (null pointer exception), IndexOutOfBoundsException (subscript out-of-bounds exception), etc. These exceptions do not check for exceptions, and you can choose to capture and process them in the program, or you can not handle them. These exceptions are generally caused by program logic errors, and programs should avoid such exceptions as much as possible from a logical perspective.
The characteristic of runtime exception is that the Java compiler will not check it. That is to say, when such an exception may occur in the program, even if it is not captured with the try-catch statement and thrown with the throws clause, it will be compiled and passed.
Non-runtime exception (compilation exception): is an exception other than RuntimeException, and belongs to the Exception class and its subclasses in terms of type. From the perspective of program syntax, it is an exception that must be processed. If it is not processed, the program cannot be compiled and passed. Such as IOException, SQLException, etc., and user-defined Exception exceptions, in general, no custom checking exceptions are checked.
3. Exception handling mechanism
In Java applications, the exception handling mechanism is: throw exceptions and catch exceptions.
Throw an exception: When an error occurs in a method and raises an exception, the method creates an exception object and delivers it to the runtime system. The exception object contains exception information such as the exception type and program status when the exception occurs. The runtime system is responsible for finding and executing code to handle exceptions.
Catch exception: After the method throws an exception, the runtime system will be turned to looking for a suitable exception handler. A potential exception handler is a collection of methods that remain in the call stack in turn when an exception occurs. When the exception type that the exception processor can handle is consistent with the exception type thrown by the method, it is a suitable exception processor. The runtime system starts with the method where an exception occurs, and then looks back at the methods on the call stack in turn until it finds a method containing a suitable exception handler and executes it. When the runtime system traverses the call stack and does not find a suitable exception handler, the runtime system terminates. At the same time, it means the termination of the Java program.
For runtime exceptions, errors or detectable exceptions, the exception handling methods required by Java technology are different.
Due to the undetectable runtime exceptions, in order to implement the application more reasonably and easily, Java stipulates that runtime exceptions will be automatically thrown by the Java runtime system, allowing the application to ignore runtime exceptions.
For errors that may occur during method operation, Java allows the method to not throw any declaration when the method is not to be captured. Because most Error exceptions are situations that can never be allowed to occur, and are also exceptions that reasonable applications should not catch.
For all checkable exceptions, Java stipulates that a method must be caught, or declared outside the throw method. That is, when a method chooses not to catch a checkable exception, it must declare that the exception will be thrown.
A method that can catch exceptions requires providing a corresponding type of exception handler. The caught exception may be caused by an exception raised and thrown by its own statement, or an exception thrown by a called method or Java runtime system, etc. In other words, the exception that a method can catch must be an exception thrown by Java code somewhere. Simply put, exceptions are always thrown first and then caught.
Any Java code can throw exceptions, such as: code written by yourself, code from the Java development environment package, or Java runtime system. No matter who it is, you can throw an exception through the Java throw statement.
Any exception thrown from the method must be used with the throws clause.
Catch exceptions are achieved through try-catch statements or try-catch-finally statements.
Generally speaking, Java stipulates that checkable exceptions must be caught or declared thrown. Allows to ignore unchecked RuntimeException and Error.
3.1 Catch exceptions: try, catch and finally
1.try-catch statement
In Java, exceptions are caught by a try-catch statement. Its general syntax form is:
try { // Program code where exceptions may occur} catch (Type1 id1){ //Catch and deal with exception type thrown by try Type1 } catch (Type2 id2){ //Catch and deal with exception type thrown by try Type2 }A pair of braces after the keyword try wraps a piece of code that may have an exception, which is called a monitoring area. If an exception occurs during the Java method during running, an exception object is created. Throw the exception outside the monitoring area, and the Java runtime system tries to find a matching catch clause to catch the exception. If there is a matching catch clause, run its exception handling code and the try-catch statement ends.
The principle of matching is: if the thrown exception object belongs to the exception class of the catch clause or belongs to a subclass of the exception class, it is considered that the generated exception object matches the exception type caught by the catch block.
Example 1 Catch the "dividter is 0" exception thrown by the throw statement.
public class TestException { public static void main(String[] args) { int a = 6; int b = 0; try { // try monitoring area if (b == 0) throw new ArithmeticException(); // throw exception through throw statement System.out.println("The value of a/b is: " + a / b); } catch (ArithmeticException e) { // catch catch exception System.out.println("The program has an exception, and the variable b cannot be 0."); } System.out.println("The program ends normally."); } }Running result: The program has an exception and the variable b cannot be 0.
The program ends normally.
Example 1 In the try monitoring area, use if statement to judge. When the error condition of "divider is 0" is established, an ArithmeticException exception is created, and the throw statement throws the exception to the Java runtime system. The system finds a matching exception handler catch and runs the corresponding exception handling code. Print out "The program has an exception, and the variable b cannot be 0." The try-catch statement ends and continues the program flow.
In fact, ArithmeticException such as "divider is 0" is a subclass of RuntimException. The runtime exception will be automatically thrown by the runtime system, and there is no need to use a throw statement.
Example 2: Catch the ArithmeticException exception caused by the "divider is 0" automatically throwing during the runtime system.
public static void main(String[] args) { int a = 6; int b = 0; try { System.out.println("The value of a/b is: " + a / b); } catch (ArithmeticException e) { System.out.println("The program has an exception, and the variable b cannot be 0."); } System.out.println("The program ends normally."); } }Running result: The program has an exception and the variable b cannot be 0.
The program ends normally.
Statement in Example 2:
System.out.println("a/b's value is: " + a/b);An error of "divider is 0" was generated during runtime, and an ArithmeticException exception was raised. The runtime system creates an exception object and throws a monitoring area, instead matches the appropriate exception handler catch, and executes the corresponding exception handling code.
Since the cost of checking runtime exceptions is much greater than the benefits of catching exceptions, runtime exceptions cannot be detected. The Java compiler allows to ignore runtime exceptions, and a method can neither catch nor declare throwing runtime exceptions.
Example 3: No catch or declare that the runtime exception is thrown.
public class TestException { public static void main(String[] args) { int a, b; a = 6; b = 0; // The value of divisor b is 0 System.out.println(a / b); } }Running results:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.TestException.main(TestException.java:8)
Example 4 The program may have an exception of divisor 0 and an exception of array subscript out-of-bounds.
public class TestException { public static void main(String[] args) { int[] intArray = new int[3]; try { for (int i = 0; i <= intArray.length; i++) { intArray[i] = i; System.out.println("intArray[" + i + "] = " + intArray[i]); System.out.println("intArray[" + i + "]module" + (i - 2) + "values: " + intArray[i] % (i - 2)); } } catch (ArrayIndexOutOfBoundsException e) { System.out.println("intArray array subscript out-of-bounds exception."); } catch (ArithmeticException e) { System.out.println("Exception of divisor 0."); } System.out.println("Program ends normally."); } }Running results:
intArray[0] = 0
intArray[0]Module-2 value: 0
intArray[1] = 1
The value of intArray[1] modulo-1: 0
intArray[2] = 2
Exception of divisor 0.
The program ends normally.
Example 5 The program may experience an exception of divisor 0, and an exception of array subscripts may also occur. During the program running, the ArithmeticException exception type matches first, so the matching catch statement is executed:
catch (ArithmeticException e){ System.out.println("Exception of divisor 0."); }It should be noted that once a catch catch catches the matching exception type, it will enter the exception handling code. Once the processing is finished, it means that the entire try-catch statement ends. Other catch clauses no longer have the chance to match and catch exception types.
Java describes exception types through exception classes, and the hierarchy of exception classes is shown in Figure 1. For exception programs with multiple catch clauses, you should try to put the catch clause that catches the underlying exception class first, and try to put the catch clause that catches the relatively high-level exception class later. Otherwise, the catch clause that catches the underlying exception class will likely be blocked.
The RuntimeException exception class includes various common exceptions at runtime, and the ArithmeticException class and the ArrayIndexOutOfBoundsException class are both subclasses. Therefore, the catch clause of the RuntimeException exception class should be placed at the end, otherwise it may block the subsequent exception handling or cause a compilation error.
2. try-catch-finally statement
The try-catch statement can also include the third part, which is the finally clause. It indicates what should be executed regardless of whether an exception occurs or not. The general syntax form of the try-catch-finally statement is:
try { // Program code that may occur exception} catch (Type1 id1) { // Catch and process the exception type thrown by try Type1 } catch (Type2 id2) { // Catch and process the exception type thrown by try Type2 } finally { // Block of statements that will be executed regardless of whether an exception occurs}Example 6 Exception handler with finally clause.
public class TestException { public static void main(String args[]) { int i = 0; String greetings[] = { " Hello world !", " Hello World !! ", " HELLO WORLD !!!" }; while (i < 4) { try { // Pay special attention to the design of loop control variable i to avoid causing infinite loops System.out.println(greetings[i++]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("ArraySubscript out-of-bounds exception"); } finally { System.out.println("--------------------------"); } } } }Running results:
Hello world!
--------------------------------
Hello World !!
--------------------------------
HELLO WORLD!!!
--------------------------------
Array subscript out of bounds exception
--------------------------------
In Example 6, please pay special attention to the design of the statement block in the try clause. If the design is as follows, a dead loop will occur. If designed as:
try { System.out.println (greetings[i]); i++; }summary:
try block: used to catch exceptions. Thereafter, zero or more catch blocks can be connected. If there is no catch block, it must be followed by a finally block.
catch block: Used to handle exceptions caught by try.
finally block: The statements in the finally block will be executed regardless of whether the exception is caught or processed. When a return statement is encountered in a try block or catch block, the finally statement block will
Executes before the method returns. In the following 4 special cases, the finally block will not be executed:
1) An exception occurred in the finally statement block.
2) Use System.exit() in the previous code to exit the program.
3) The thread where the program is located dies.
4) Turn off the CPU.
3. try-catch-finally rule (grammatical rule for exception handling statement):
1) A catch or finally block must be added after the try. After the try block, the catch and finally blocks can be connected at the same time, but there is at least one block.
2) The block order must be followed: If the code uses both catch and finally blocks, the catch block must be placed after the try block.
3) The catch block is related to the type of the corresponding exception class.
4) A try block may have multiple catch blocks. If so, the first matching block is executed. That is, the Java virtual machine matches the actual thrown exception objects with the exception types declared by each catch code block in sequence. If the exception object is an exception type or an instance of its subclass, the catch code block will be executed and no other catch code block will be executed.
5) Nested try-catch-finally structure.
6) In the try-catch-finally structure, an exception can be re-throwed.
7) In addition to the following situations, the execution of finally ends: the JVM terminates prematurely (called System.exit(int)); throws an unhandled exception in the finally block; the computer is powered off, fired, or is attacked by a virus.
4. The execution order of try, catch, and finally statement blocks:
1) When the try does not catch an exception: the statements in the try statement block are executed one by one, and the program will skip the catch statement block and execute the finally statement block and subsequent statements;
2) When the try catches an exception, the catch statement block does not handle this exception: when an exception occurs in a statement in the try statement block and the catch statement block that does not handle this exception, the exception will be thrown to the JVM for processing, and the statement in the finally statement block will still be executed, but the statement after the finally statement block will not be executed;
3) When a try catches an exception, the catch statement block will handle this exception: it is executed in the try statement block in order. When an exception occurs when an exception occurs in a certain statement, the program will jump to the catch statement block and match it one by one. Find the corresponding handler. Other catch statement blocks will not be executed. In the try statement block, the statement after an exception occurs will not be executed. After the catch statement block is executed, the statement in the finally statement block will be executed, and finally the statement after the finally statement block will be executed;
Illustration of the execution of try, catch, and finally statement blocks:
Figure 2 illustrates the execution of try, catch, and finally statement blocks
3.2 Throw an exception
Any Java code can throw exceptions, such as: code written by yourself, code from the Java development environment package, or Java runtime system. No matter who it is, you can throw an exception through the Java throw statement. Any exception thrown from the method must be used with the throws clause.
1. throws throw exception
If a method may have an exception but does not have the ability to handle such an exception, you can use the throws clause to declare the thrown exception at the method declaration. For example, a car may fail when running, and the car itself cannot handle this failure, so let the driver deal with it.
The throws statement is used to declare the type of exception to throw when the method is defined. If the Exception exception type is thrown, the method is declared to throw all exceptions. Multiple exceptions can be split using commas. The syntax format of the throws statement is:
methodname throws Exception1,Exception2,..,ExceptionN { } throws after the method name Exception1,Exception2,...,ExceptionN is the list of exceptions to be thrown. When a method throws an exception list of exceptions, the method will not handle exceptions of these types and their subclass types, but will be thrown to the method that calls the method and will be handled by it. For example:
import java.lang.Exception; public class TestException { static void pop() throws NegativeArraySizeException { // Define the method and throw the NegativeArraySizeException exception int[] arr = new int[-3]; // Create an array} public static void main(String[] args) { // Main method try { // try statement handles exception information pop(); // Call the pop() method} catch (NegativeArraySizeException e) { System.out.println("Exception thrown by the pop() method"); // Output exception information} } }After throwing the exception to the caller using the throws keyword, if the caller does not want to handle the exception, you can continue to throw it up, but in the end there must be a caller who can handle the exception.
The pop method does not handle the exception NegativeArraySizeException, but is handled by the main function.
The rule for Throws to throw exceptions:
1) If it is an unchecked exception, that is, Error, RuntimeException or their subclasses, you can declare the exception to be thrown without using the throws keyword, and the compilation will still pass smoothly, but it will be thrown by the system at runtime.
2) Any checked exceptions that can be thrown by the method must be declared. That is, if a method may have a checkable exception, it will either be caught with a try-catch statement or throw it with a throws clause declaration, otherwise it will cause a compile error.
3) Only when an exception is thrown, the caller of the method must handle or re-throw the exception. When the method caller is unable to handle the exception, it should continue to throw it instead of swallowing it whole.
4) The calling method must follow any checkable exception handling and declaration rules. If a method is overwritten, exceptions that are different from the overwritten method cannot be declared. Any exception declared must be a similar or subclass of the exception declared by the overridden method.
For example:
void method1() throws IOException{} //Legal//Compilation error, IOException must be caught or declared to throw void method2(){ method1(); } //Legal, declare to throw IOException void method3()throws IOException { method1(); } //Legal, declare to throw Exception, IOException is a subclass of Exception void method4()throws Exception { method1(); } //Legal, capture IOException void method5(){ try{ method1(); } catch(IOException e){…} } //Compilation error, you must catch or declare thrown Exception void method6(){ try{ method1(); }catch(IOException e){throw new Exception();} } //Legal, declare throw Exception void method7()throws Exception{ try{ method1(); }catch(IOException e){throw new Exception();} } The basis for determining that an exception may occur in a method is as follows:
1) There is a throw statement in the method. For example, the catch code block of the above method7() method has a throw statement.
2) Other methods are called, and other methods use throws clause to declare some exception to throw. For example, the method3() method calls the method1() method, and the method1() method declares that an IOException is thrown, so an IOException may occur in the method3() method.
2. Use throw to throw exception
throw always appears in the function body and is used to throw an exception of type Throwable. The program will terminate immediately after the throw statement, the statement after it cannot be executed, and then in all the try blocks containing it (perhaps in the upper-level calling function) look for try blocks containing the catch clause that matches it from the inside out.
We know that exceptions are instance objects of exception class, and we can create instance objects of exception class to be thrown through throw statement. The syntax format of this statement is:
throw new exceptionname;
For example, throw an exception object of the IOException class:
throw new IOException;
It should be noted that throws only instance objects that can throw class Throwable or subclasses. The following operation is incorrect:
throw new String("exception");This is because String is not a subclass of the Throwable class.
If a check exception is thrown, you should also declare the type of exception that the method may throw in the method header. The caller of this method must also check for handling the thrown exception.
If all methods throw the acquired exception layer by layer, the JVM will eventually process it, and the processing is also very simple, which is to print the exception message and stack information. If an Error or RuntimeException is thrown, the caller of the method has the option to handle the exception.
package Test; import java.lang.Exception; public class TestException { static int quotient(int x, int y) throws MyException { // Define method to throw an exception if (y < 0) { // Determine whether the parameter is less than 0 throw new MyException("The divisor cannot be a negative number"); // Exception information} return x/y; // Return value} public static void main(String args[]) { // Main method int a =3; int b =0; try { // try statement contains statements that may have exceptions int result = quotient(a, b); // Call method quoteent() } catch (MyException e) { // Handle custom exception System.out.println(e.getMessage()); // Output exception information} catch (ArithmeticException e) { // Handle ArithmeticException exception System.out.println("Divorceipt cannot be 0"); // Output prompt information} catch (Exception e) { // Handle other exceptions System.out.println("Other exceptions occurred in the program"); // Output prompt information} } } class MyException extends Exception { // Create custom exception class String message; // Define String type variable public MyException(String ErrorMessagr) { // Parent class method message = ErrorMessagr; } public String getMessage() { // Override getMessage() method return message; } }3.3 Exception chain
1) If quotient(3,-1) is called, a MyException exception will occur and the program will be transferred to the catch (MyException e) code block to execute;
2) If quotient(5,0) is called, an ArithmeticException exception will be raised due to the "divider is 0" error. It belongs to the runtime exception class and is automatically thrown by the Java runtime system. The quotient() method does not catch the ArithmeticException exception. The Java runtime system will search for the main method along the method call stack and upload the thrown exception to the caller of the quotient() method:
int result = quotient(a, b); // Call method quotient()
Since this statement is in the try monitoring area, the ArithmeticException with "divider is 0" passed back is thrown by the Java runtime system and matches the catch clause:
catch (ArithmeticException e) { // Handle ArithmeticException exception System.out.println("The divisor cannot be 0"); // Output prompt information}The processing result is that the output "divider cannot be 0". Java, a processing mechanism that passes exception information upward, forms an exception chain.
The checkable exception thrown by the Java method will be passed to the calling method with processing capability based on the call stack and along the hierarchy of the method call, and the highest level will be until the main method. If the exception is passed to the main method, but the main does not have the ability to handle it and does not throw the exception through the throws declaration, a compilation error may occur.
3) If other exceptions occur, catch (Exception e) will be used to catch. Since Exception is the parent class of all exception classes, if the catch (Exception e) code block is placed in front of the other two code blocks, the subsequent code blocks will never be executed, which makes no sense, so the order of catch statements cannot be replaced.
3.4 Common methods in Throwable class
Note: The parameter e of Exception type in brackets after the catch keyword. Exception is the variable type passed to the catch code block by the try code block, and e is the variable name. The statement "e.getMessage();" in the catch code block is used to output the error properties. Usually, 3 functions are commonly used to obtain information about exceptions:
getCause(): Returns the reason for throwing the exception. If cause does not exist or is unknown, return null.
getMeage(): Returns the exception message information.
printStackTrace(): The stack trace of the object is output to the error output stream as the value of the field System.err.
Sometimes, for the sake of simplicity, the code after the catch statement is ignored, so the try-catch statement becomes a decoration. Once an exception occurs during the program, the exception will be ignored, and the reason for the error is difficult to find.
5. Common Java exceptions
Some exceptions are provided in Java to describe frequently occurring errors. For these exceptions, some require programmers to capture or declare thrown, while others are automatically captured and processed by Java virtual machines. Common exception classes in Java:
1. runtimeException subclass:
1. java.lang.ArrayIndexOutOfBoundsException
The array index is out of bounds. Thrown when the index value of the array is negative or greater than or equal to the array size.
2.java.lang.ArithmeticException
Arithmetic conditions are abnormal. For example: integer division zero, etc.
3.java.lang.NullPointerException
Null pointer exception. This exception is thrown when the application tries to use null where the object is required. For example: calling an instance method of a null object, accessing the properties of a null object, calculating the length of a null object, throwing null using a throw statement, etc.
4. java.lang.ClassNotFoundException
The class exception was not found. This exception is thrown when the application attempts to construct a class based on a class name in the form of a string, and the class file with the corresponding name cannot be found after traversing CLASSPAH.
5. java.lang.NegativeArraySizeException The array length is negative exception
6. java.lang.ArrayStoreException The exception thrown by an incompatible value in the array
7. java.lang.SecurityException security exception
8. java.lang.IllegalArgumentException Illegal parameter exception
2.IOException
IOException: An exception that may occur when operating the input stream and the output stream.
EOFException file ended exception
FileNotFoundException The file is not found
3. Others
ClassCastException Type conversion exception class
ArrayStoreException thrown by an array containing incompatible values
SQLException Operating database exception class
NoSuchFieldException field not found
NoSuchMethodException method not found the thrown exception
NumberFormatException The exception thrown by converting a string to a number
StringIndexOutOfBoundsException The string index throws an exception outside the range
IllegalAccessException does not allow access to certain types of exceptions
InstantiationException When the application attempts to create an instance of a class using the newInstance() method in the Class class, and the specified class object cannot be instantiated, this exception is thrown.
6. Custom exceptions
Use Java built-in exception classes to describe most exceptions that occur during programming. In addition, users can also customize exceptions. User-defined exception class, just inherit the Exception class.
Using custom exception classes in a program can be roughly divided into the following steps.
(1) Create a custom exception class.
(2) Throw an exception object through the throw keyword in the method.
(3) If the exception is handled in the method where the exception is currently thrown, you can use the try-catch statement to catch and process it; otherwise, the throws keyword is used to indicate the exception to be thrown to the method caller at the declaration of the method and continue to the next operation.
(4) Catch and handle exceptions in the caller whose exception method occurs.
The "throw exception using throw" example above has been mentioned.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.