Dark Horse programmer-java Abnormal explanation

Source: Internet
Author: User
Tags throwable

--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 from Throwable, known as Exception, 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 the catchIn the ExceptionInto StringIndexOutOfBoundsException, the output is also String index out of range: 3, as follows: here ExceptionIs StringIndexOutOfBoundsExceptionThe 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 exception ExceptionThe inheritance diagram can be clearly known ExceptionThe relationship of the parent class and its subclasses, the superclass is ThrowableErrorAnd Exceptionof the common superclass), ThrowableThe Super class is Object(except for the direct or indirect superclass of all classes in Java outside of itself). To ExceptionThe end class is inherited from the Exception

When tryWhen 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 is StringIndexOutOfBoundsExceptionException, this exception is only System.out.println("Hi".charAt(0));will only be produced. and System.out.println(123 / 0);This statement produces another exception, called ArithmeticException, 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. Plus ArithmeticExceptionExceptions 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 of catch? Of course you can use the same as the first example ExceptionTo receive all exceptions, but then there is the problem that all exceptions will be handled uniformly, so use Exceptionand 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 capture finallyWith catchis similar in usage, but finallyAfter no type, finallyThe function is as try...catch...finallyThe inevitable implementation of the paragraph. Other words tryThe code inside is either generating or not producing an exception and will eventually execute finallyWithin 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, the finallyWriting 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 few finallyThe 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 executes finallyThe 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; }}
When finallyIt's been there before. returnStatement, the contents of the returned value are pushed to the stack, so the finallyModified in numThe value is not affected by the final mainfunction to receive the contents of the return value, which also reflects the finallyWill 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) {            }        }    }}
So finallyThe 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 execute finallyThe 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 throws throwsFor exception handling, you can use the try...catch, you can use try...catch...finally, you can also use try..finallyAnd of course there are other ways that you can use throwsThrow an exception to the upper layer, where the previous layer refers to the mainFunction call methodMethod, for methodMethod for mainThe 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 be throwsLater use ,, and throwing an exception is used throwTo 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 inherit ExceptionCan, or inherit ExceptionSub-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 thrown RuntimeExceptionOr RuntimeExceptionSub-class without using the throwsAfter 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

Related Article

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.