1. Exception:
1.1: errors and exceptions are two concepts: errors need to be avoided, and exceptions are foreseeable and controllable.
Get
1.2: handling exception: try... Catch... Finally
If throw is used, the method name must be modified using throws.
Public void sayHello () throws Exception {}.
To call this method, or use try .. Catch exception, or throws
Exception is handed over to the next method to use it.
1.3: try {if the following statement is incorrect, skip to the catch statement without executing the next sentence}
1.4: Statements in finally can be executed in any way. Even if return is used in try and catch
Finally will also execute.
1.5: the difference between throw and throws: throw: throwing an exception object. Throws: Declaration of the modifier.
1.6: a try can be followed by multiple catch, because the code in try may have many errors and error types.
Or the types are different, so there can be multiple, but find the corresponding, the following catch will not be executed
.. Catch.
1.7: exceptions are generally divided into two categories: Checked exceptions and non-checked or runtime exceptions:
RuntimeException. Skip this step.
1.8: custom Exception class: the class inherited from the Exception is called the custom Exception class.
The code is as follows: |
Copy code |
Public class myException extends Exception { Public void printstrackance (){ } } |
1.9:
Three methods to handle exceptions: the system automatically handles the exceptions by using try ~ Catch ~ Finally statement, throw statement directly throw
An exception occurs or an exception is thrown indirectly using the throws statement.
5. Example
The following is an example: TestServlet calls TestDB and TestPsi (with code). If an exception occurs, how can we quickly solve the exception error of the program.
During the development of the entire project, specify the error code table and classify it. Such as PSI, database exception code, application exception code, XML exception, and network communication exception;
Use your own exception class. When an exception is encountered, the thrown exception carries the path of the error class or exception method:
For example, setFlag ("PSI001 ");
The code is as follows: |
Copy code |
Throw new WhcaException ("JB: TestA M: exe1" + e. getMessage ); |
Here: PSI001 is the error code, "JB: TestA M: exe1" is the exception chain, and e. getMessage is the exception information.
For example, the error message list is: JB: TestB M: exe2 JB: TestA M: exe1 java. SQL. SQLException, indicating that the TestB method exe2 calls the TestA method exe1 and an exception occurs when operating the database. Then you can quickly and accurately locate the method of that class that encountered an exception.
Note: (abbreviated) JB: JavaBean M: Method
Database access