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
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 JavaProgramThe exception capture method that is often used by members is very simple and will not be repeated. The above program execution result:
Exception in thread "Main" Java. lang. arithmeticexception:/by zeroat COM. jointsky. exception. testtrycatch. try (testtrycatch. java: 6) at com. jointsky. exception. testtrycatch. main (testtrycatch. java: 15)
2. Throws exception
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: if the main function is compiled without throws exception, it does not pass testthrows. throws ();}}
This example mainly describes the difference between the two keywords throws and throw. The execution result is as follows:
Exception in thread "Main" Java. lang. exception: except 0. Exception:/by zeroat COM. jointsky. exception. testthrows. throws (testthrows. java: 12) at com. jointsky. exception. testthrows. main (testthrows. java: 20)
3. Self-write exception class
Public class diyexception {public static void testdiy () {system. Out. println ("this is diyexception ");}}
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: Try {} catch () {} is not added and try {testextendsexception is not used for compilation. throws ();} catch (exception e) {// todo auto-generated catch blocke. printstacktrace ();}}}
Exception Handling can also be compiled by yourself. The execution result of the above program:
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.
Dml@2012.11.6