Simple principle and application of exception handling mechanism
Execption can be divided into Java standard definition of exceptions and programmer custom exceptions 2 kinds
(1) One is that when a program violates a Java language rule, the Java Virtual machine represents the error that occurs as an exception. Here the syntax rules refer to the semantic checks built into the Java class library.
For example int i = 2/0 or String str = null;str.length ();
(2) Another case is that Java allows programmers to extend this semantic check, and programmers can create their own exceptions and freely choose when to throw exceptions with the throw keyword.
For example Exception ex = new Exception ("This is my custom exception information"); throw ex;
All exceptions are subclasses of thowable.
Exception handling is parallel to program execution.
try{ // may find exception statement block }catch(exception type, e) { // EXECUTE statement block when exception occurs } finnally{ // statement block executed regardless of whether an exception occurred }
Second, the exception of the treatment method
Includes catch exception and top throw exception
1. Catching exceptions
Take the example of capturing int i=2/0
try { int i = 2/0; Catch (Exception ex) {// The parent class of all exceptions exception ex.printstacktrace () ; // Handling Exceptions SYSTEM.OUT.PRINTLN ("Exception information:" + ex.getmessage ()); } finally { System.out.println ("Free resources, subsequent code, code that must be executed"); } System.out.println ("continue running");
The output result is
Ex.printstacktrace () indicates that detailed exception information is printed to the console
2, top throw abnormal throws
With String str =null;
Str.length (); (not instantiated) as an example
Packagetest;ImportCom.hanqi.ThrowEX; Public classTest { Public voidTest ()throwsException {//with throws String Str=NULL; Str.length (); } Public Static voidMain (string[] args) {Throwex te=NewThrowex (); With throwTry{te.test (); } Catch(Exception e) {//TODO Auto-generated catch blockE.printstacktrace (); System.out.println ("Exception information is" +e.getmessage ()); } }}
E.printstacktrace () indicates that detailed exception information is printed to the console
java--simple principle and application of exception handling mechanism