1. Try & catch
An exception is a running error. It can be generated by the system during Java runtime, or manually by code. Five keywords try catch throw throws finally
Try {}
Catch (exceptiontype1 E1 ){...}
Catch (exceptiontype2 E2) {system. Out. println (E2 );}
...
Finally {}
All exception types are subclasses of the built-in class throwable. Two branches: exception and error. The exception class has an important subclass: runtimeexception. The error class defines exceptions that do not need to be captured by programs in the general environment. It is used by the Java runtime system to indicate that some errors have occurred during the runtime, stack Overflow is an example.
Exception Handling has two advantages: Allow error fixing and automatic termination of the blocking program.
Once an exception is thrown, the program control will be transferred from the try code block to the catch code block,No "return"To the try code block. After the catch is executed, continue to the next line of the entire try/catch code block. The scope of the catch clause is limited to the statements specified by the previous try statement. Catch cannot catch exceptions thrown by another try statement,However, the nested try statement is an exception.!
You cannot use try for a single statement.
Multiple catch statements.When an exception is thrown, check each catch statement in sequence, execute the first catch clause that can match the type and exception, ignore other catch statements, and continue to execute the subsequent code. The exception subclass must be located before all superclasses. The Catch statement that uses a super class will capture the exception of this superclass and all its subclasses. For example, arithmeticexception must be caught before exception.
Nested try statement.One Try statement can be located in another try statement. Every time a try statement exception occurs, the context is pushed into the stack. If the try statement in the lower layer does not provide catch for a specific exception, the stack will pop up the try statement to check whether the catch handler of the next try statement matches until a matched catch statement is found or all try statements are checked. When a method call is involved, there may be non-obvious try statement nesting. A try code block may contain a call to a method, there is another try statement in this method.
Multiple captures. Catch (arithmeticexception|
ArrayindexoutofboundsexceptionE){...}
2. Throw
Throw throwableinstance; // throwableinstance must be a throwable or its subclass type object. Basic Types and non-throwable classes cannot be used as exceptions. You can obtain the throwable object in two ways: using parameters in the catch clause and using new to create a throwable object.
The execution flow after the throw statement is stopped immediately, and all subsequent statements are not executed. Check the latest try code block, match catch, and so on. For example,
Class throwdemo {
Static void
Demoproc (){
Try {
Thrownew nullpointerexception ("Demo"); // constructs an nullpointerexception instance.
} Catch (nullpointereffectione ){
System. Out. println ("caught inside demoproc .")
Throw E;
}
}
Public static main (string ARGs []) {
Try {
Demoproc (); // No need to create an object
} Catch (nullpointereffectione ){
System. Out. println ("recaught:" + E );
}
}
}
// The output is caught inside demoproc.
Recaught: Java. Lang. nullpointerexception:Demo.
Many built-in Java runtime exceptions include at least two constructor functions: one with no parameters and the other with a string parameter. If the latter is used, the parameter specifies a string used to describe the exception.
3. Throws
The throws statement is provided in the method declaration. The throws clause lists all possible exception types thrown by a method and must be declared. Otherwise, an error occurs during compilation.
Type method_name (parameter-list)Throws exception-list{...} // Exception-list are separated by commas.
4. Finally
An exception may cause the method to be returned earlier than expected. In this case, finally can solve problems such as file Shutdown (bypassing the exception mechanism.
Whether or not an exception is thrown, the finally code block is executed. Whether it is an uncaptured exception or an explicit Return Statement, the finally clause will be executed before the return.
5. Java built-in exceptions
Java's unchecked runtimeexception subclass defined in Java. Lang (17 in total)
Reference: http://www.cnblogs.com/qinqinmeiren/archive/2010/10/14/2151702.html
Http://blog.sina.com.cn/s/blog_4d8498800100dcm3.html
Nullpointerexception-null pointer reference exception
Classcastexception-type forced conversion exception
Enumconstantnotpresentexception tries to use undefined enumerated Value
Illegalargumentexception-
An error occurred while passing invalid parameters.
Illegalmonitorstateexception-
Illegal monitoring operations, such as waiting for unlocked threads
Illegalstateexception-
The environment or application is in an incorrect state
Illegalthreadstateexception-
The requested operation is not compatible with the current thread status
Arithmeticexception-arithmetic operation exception
Arrayindexoutofboundsexception array index out of bounds
Arraystoreexception-An error occurred while saving an incompatible object with the declared type to the array.
IndexoutofboundsexceptioN
-Subscript out-of-bounds exception
NegativearraysizeexceptiOn
-An error occurred while creating an array of negative values.
Numberformatexception-numeric format exception
Securityexception-security exception
Stringindexoutofbounds tries to index outside the string Boundary
Typenotpresentexception-
Type not found
UnsupportedoperationexcePtion
-The operation is not supported.
Checked exceptions defined by Java in Java. Lang
Classnotfoundexception class not found
Clonenotsupportedexception tries to copy objects that do not implement the cloneable Interface
Illegalaccessexception: access to the class is denied.
Instantiationexception tries to create an object for an abstract class or interface
Interruptedexception one thread is interrupted by another thread
The domain variable of the nosuchfieldexception request does not exist.
Nosuchmethodexception the requested method does not exist
Reflection-related exception subclass
6. Create your own exception subclass
You only need to define the subclass of exception. Subclasses do not need to actually implement anything-as long as they exist in the type system, they can be used as exceptions.
The exception class does not define any methods for itself, of course it inherits the methods provided by throwable (see the link: http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html ). The exception class defines four constructors, two of which support chained exceptions and the other two are as follows: exception ()
Exception (string MSG)
For example,
class MyException extends Exception {private int detail;MyException(int a) {detail = a;}public String toString() {return "MyException[" + detail + "]";}}class ExceptionDemo {static void compute(int a) throws MyException {System.out.println("Called compute(" + a + ")");if(a > 10) throw new MyException(a);System.out.println("Normal exit");}public static void main(String args[]) {try {compute(1);compute(20);} catch(MyException e) {System.out.println("Caught " + e);}}}
Compile javac A. Java to generate exceptiondemo. Class and myexception. Class.
Run Java exceptiondemo. The result is as follows:
Called compute (1)
Normal exit
Called compute (20)
Caught myexception [20]
7. chained exceptions
Is associated with another exception. The second exception describes the cause of the first exception. Chained exceptions can contain any depth required.
To use a chained exception, add two constructors and methods to the throwable class:
Throwable (throwable causeexc) throwable (string MSG, throwable causeexc)
// Causeexc is the exception that causes the current exception. MSG allows you to specify the exception description at the same time.
Throwable getcause () throwable initcause (throwable causeexc)
// Getcause () returns the exception that causes the current exception. If no exception exists, null is returned,
// Initcause () associates causeexc with a call exception and returns a reference to the exception. Each exception object can call initcause () only once. If an exception is thrown by setting the constructor, therefore, you cannot use initcause () to set it. Generally, initcause () is used to set the cause for the legacy exception classes that do not support the two attached constructors described above.
On February 10