Dark Horse programmer-java Abnormal explanation

Source: Internet
Author: User

--java Training, Android training, iOS training,. NET training, look forward to communicating with you! ——-

Exceptions to the exception in Java are those that hinder the current program from running, which may cause the program to fail, such as 0 errors in the program, array subscript out of bounds, and so on. Exceptions are encapsulated in Java as a class that inherits fromThrowable, known asException, it has a lot of sub-categories, respectively, describes a lot of common anomalies in the system, the appearance of these anomalies makes the program when the process of dealing with some problems is particularly convenient, the following are some simple use cases. General format for exception capture
/** * javac ExceptionDemo.javac * java ExceptionDemo * 输出:String index out of range: 3 */class ExceptionDemo {    publicstaticvoidmain(String[] args) {        try {            // 可能产生异常的代码放到try内            System.out.println("Hi".charAt(3));        catch(Exception e) {            // 对异常的处理            System.out.println(e.getMessage());        }    }}
When thecatchIn theExceptionIntoStringIndexOutOfBoundsException, the output is alsoString index out of range: 3, as follows: hereExceptionIsStringIndexOutOfBoundsExceptionThe parent class, the object of the subclass is assigned to the type of the parent class, which is called polymorphic in Java.
/** * 输出:String index out of range: 3 */class ExceptionDemo {    publicstaticvoidmain(String[] args) {        try {            // 可能产生异常的代码放到try内            System.out.println("Hi".charAt(3));        catch(StringIndexOutOfBoundsException e) {            // 对异常的处理            System.out.println(e.getMessage());        }    }}
An inherited relationship from an exceptionExceptionThe inheritance diagram can be clearly knownExceptionThe relationship of the parent class and its subclasses, the superclass isThrowable(ErrorAndExceptionof the common superclass),ThrowableThe Super class isObject(except for the direct or indirect superclass of all classes in Java outside of itself). ToExceptionThe end class is inherited from theException。

WhentryWhen there are multiple statements inside, there may be multiple exceptions, and the following code, while adding an exception capture operation, does not produce an exception, and the program crashes.
/** * output: H * Exception in thre Ad "Main" Java.lang.ArithmeticException:/by Zero * at Exceptiondemo3.main (exceptiondemo3.java:10) */ class E XceptionDemo3 {public  static  void  main  (string[] args) {try {//could produce an exception to the code put in the try  System.out.println (" Hi ". CharAt (0 ));        System.out.println (123 /0 ); } catch  (stringindexoutofboundsexception e) {//to XOR        The usual processing  System.out.println (E.getmessage ()); }    }}
The reason is that although there are catch to catch the exception, the only catch isStringIndexOutOfBoundsExceptionException, this exception is onlySystem.out.println("Hi".charAt(0));will only be produced. andSystem.out.println(123 / 0);This statement produces another exception, calledArithmeticException, which is an operation exception. This exception does not have a corresponding capture statement, so the virtual machine takes the default processing, that is, to let the program crash. PlusArithmeticExceptionExceptions can be handled normally after the exception is captured, as follows:
/** * Output: H * Exception:/by zero */Class ExceptionDemo3 { Public Static void Main(string[] args) {Try{//The code that could produce the exception is put in the trySystem.out.println ("Hi". CharAt (0)); System.out.println (123/0); }Catch(Stringindexoutofboundsexception e) {//Handling of exceptionsSystem.out.println (E.getmessage ()); }Catch(ArithmeticException e) {System.out.println ("Exception:"+ e.getmessage ()); }    }}
If there is a large number of statements in the try, there will be a lot of exceptions to add a lot ofcatch? Of course you can use the same as the first exampleExceptionTo receive all exceptions, but then there is the problem that all exceptions will be handled uniformly, so useExceptionand other anomalies mixed with the situation, this situation should be noted,ExceptionBe sure to put it on the last side.catch, or the compilation will error. The correct wording is as follows:
/** * Output: H * Exception:/by zero */Class ExceptionDemo3 { Public Static void Main(string[] args) {Try{//The code that could produce the exception is put in the trySystem.out.println ("Hi". CharAt (0)); System.out.println (123/0); }Catch(Stringindexoutofboundsexception e) {//Handling of exceptionsSystem.out.println (E.getmessage ()); }Catch(ArithmeticException e) {System.out.println ("Exception:"+ e.getmessage ()); }Catch(Exception e)        {System.out.println (E.getmessage ()); }     }}
finallyAnother keyword in the keyword Java exception capturefinallyWithcatchis similar in usage, butfinallyAfter no type,finallyThe function is astry...catch...finallyThe inevitable implementation of the paragraph. Other wordstryThe code inside is either generating or not producing an exception and will eventually executefinallyWithin the code. This can be applied to some network operations, such as having a database open when accessing the database, and when an error occurred while manipulating the database, thefinallyWriting on the close database operation has played a very good role. Avoid the system opening many database connections and cannot be shut down and unable to operate, which consumes system resources very much. The same is true when accessing the network. A fewfinallyThe demo is as follows:
/** * Output: * B * C */Class ExceptionDemo4 { Public Static void Main(string[] args) {Try{intnum =4/0;//Making exceptionsSystem.out.println ("A"); }Catch(Exception e) {System.out.println ("B"); }finally{System.out.println ("C"); }    }}/** * Output: * A * B * C * *Class ExceptionDemo4 { Public Static void Main(string[] args) {Try{System.out.println ("A");intnum =4/0;//Making exceptions}Catch(Exception e) {System.out.println ("B"); }finally{System.out.println ("C"); }    }}/** * Output: * 4 * 4 * 0 * *Class ExceptionDemo4 { Public Static void Main(string[] args) {intnum =4;Try{System.out.println (num);intn =Ten/0;//Manufacturing anomaliesnum + =2;//An exception occurs immediately after the Exception handling section}Catch(Exception e)            {System.out.println (num); num =0; }finally{System.out.println (num); }    }}
tryThe code inside does not continue executing when it encounters an exception, but instead jumps to the corresponding exception-handling code snippet and executesfinallyThe code for the segment. In a function with a return value,finallyis executed as follows:
/** * Output: * try:4 * catch:4 * finally:5 * Main:4 * *Class ExceptionDemo5 { Public Static void Main(string[] args) {System.out.println ("Main:"+ method ()); } Public Static int Method() {intnum =4;Try{System.out.println ("Try:"+ num);intn =Ten/0;//Manufacturing anomalies}Catch(Exception e) {System.out.println ("catch:"+ num);returnNum }finally{num + +; System.out.println ("Finally:"+ num); }return 0; }}
WhenfinallyIt's been there before.returnStatement, the contents of the returned value are pushed to the stack, so thefinallyModified innumThe value is not affected by the finalmainfunction to receive the contents of the return value, which also reflects thefinallyWill certainly execute a point. But when it comes to this, it's another story:
ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.IOException;/** * File content is: Hello * If the system.exit (0); Comment out, the content of the file is hi */Class ExceptionDemo5 { Public Static void Main(string[] args) {Try{FileOutputStream Fout =NewFileOutputStream (NewFile ("E:\\ex.txt")); Fout.write ("Hello". GetBytes ());            Fout.close (); System.exit (0);//Direct exit system}Catch(IOException e) {        }finally{Try{FileOutputStream Fout =NewFileOutputStream (NewFile ("E:\\ex.txt")); Fout.write ("Hi". GetBytes ());            Fout.close (); }Catch(IOException e) {            }        }    }}
SofinallyThe content must be executed also to establish a re-program is still in the running state, the program has exited the virtual machine, of course, can no longer executefinallyThe content of the.try...finallyCombination

In addition try...catch...finally to a try...finally combination of methods, the catch segment is removed. If the code snippet throws an RuntimeException exception to the previous layer, the RuntimeException error will be compiled if it is not or its subclasses. ( ArithmeticException belonging to RuntimeException )

/** * Output: * method:finally * main:/by zero */Class ExceptionDemo6 { Public Static void Main(string[] args) {Try{method (); }Catch(Exception e) {System.out.println ("Main:"+ e.getmessage ()); }    } Public Static void Method() {Try{intnum =6/0; }finally{System.out.println ("Method:finally"); }    }}
Exception throwsthrowsFor exception handling, you can use thetry...catch, you can usetry...catch...finally, you can also usetry..finallyAnd of course there are other ways that you can usethrowsThrow an exception to the upper layer, where the previous layer refers to themainFunction callmethodMethod, formethodMethod formainThe function is the previous layer.
/** * 输出: * main:Hello */class ExceptionDemo7 {    publicstaticvoidmain(String[] args) {        try {            method();        catch(ClassNotFoundException e) {            System.out.println("main:" + e.getMessage());        }    }    publicstaticvoidmethodthrows ClassNotFoundException {        Class<?> c = Class.forName("Hello");    }}
When multiple exceptions are thrown, they can bethrowsLater use,, and throwing an exception is usedthrowTo achieve the following:
/** * Output: * main:-message-*/Class ExceptionDemo7 { Public Static void Main(string[] args) {Try{method (); }Catch(ClassNotFoundException e) {System.out.println ("Main:"+ e.getmessage ()); }Catch(Exception e) {System.out.println ("Main:"+ e.getmessage ()); }    } Public Static void Method()throwsClassNotFoundException, Illegalaccessexception {//class<?> C = class.forname ("Hello");        Throw(NewIllegalaccessexception ("-message-")); }}
Custom exception custom exceptions are really simple, just inheritExceptionCan, or inheritExceptionSub-class, as follows:
/** * Output: * main:my Exception */Class MyException extends Exception { Public myexception(String msg) {Super(msg); }}class ExceptionDemo7 { Public Static void Main(string[] args) {Try{method (); }Catch(MyException e) {System.out.println ("Main:"+ e.getmessage ()); }    } Public Static void Method()throwsmyexception {Throw(NewMyException ("My Exception")); }}
RuntimeExceptionIntroduction when thrownRuntimeExceptionOrRuntimeExceptionSub-class without using thethrowsAfter the method name is marked, this class of exceptions may not be handled well by capture processing, such as except that the 0 error occurs even if an exception is caught, but the result of the subsequent operation will be affected, there must be an incorrect result of the operation. In addition to the 0 exception that appears above, you do not need to add an exception type description after the method name:
/** * Output: * method:finally * main:/by zero */Class ExceptionDemo6 { Public Static void Main(string[] args) {Try{method (); }Catch(Exception e) {System.out.println ("Main:"+ e.getmessage ()); }    } Public Static void Method()/* No need to add arithmeticexception*/{hereTry{intnum =6/0; }finally{System.out.println ("Method:finally"); }    }}

Dark Horse programmer-java Abnormal explanation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.