Java Exception Handling involves a lot of principles and theories, and requires a little understanding and optimization. The source code is posted here, which only serves as an image-aware java exception handling method.
1. try catch
[Java]
Public class TestTryCatch {
Public static void Try (){
Int I = 1/0;
Try {
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
TestTryCatch. Try ();
}
}
Try catch is a common exception capture method used by java Programmers. It is very simple and will not be repeated. The above program execution result:
[Plain]
Exception in thread "main" java. lang. ArithmeticException:/by zero
At com. jointsky. exception. TestTryCatch. Try (TestTryCatch. java: 6)
At com. jointsky. exception. TestTryCatch. main (TestTryCatch. java: 15)
2. throws Exception
[Java]
Public class TestThrows {
Public static void Throws () throws Exception {
Try {
Int I = 1/0;
} Catch (Exception e ){
Throw new Exception ("except 0 Exception:" + e. getMessage ());
}
}
Public static void main (String [] args) throws Exception {
// Note: The main function fails to be compiled without throws Exception.
TestThrows. Throws ();
}
}
This example mainly describes the difference between the two keywords throws and throw. The execution result is as follows:
[Plain]
Exception in thread "main" java. lang. Exception: Except for 0 Exception:/by zero
At com. jointsky. exception. TestThrows. Throws (TestThrows. java: 12)
At com. jointsky. exception. TestThrows. main (TestThrows. java: 20)
3. Self-write exception class
[Java]
Public class DIYException {
Public static void TestDIY (){
System. out. println ("This is DIYException ");
}
}
[Java]
Public class TestExtendsException extends DIYException {
Public static void Throws () throws Exception {
Try {
Int I = 1/0;
} Catch (Exception e ){
DIYException. TestDIY ();
}
}
Public static void main (String [] args ){
// Note: The try {} catch () {} compilation fails.
Try {
TestExtendsException. Throws ();
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
}
}
Exception Handling can also be compiled by yourself. The execution result of the above program:
[Plain]
This is DIYException
P.S.
The problem is always inexplicable. Many things need to be accumulated a little bit. This requires a process, patience, preparation, and other inexplicable problems.