Java exception details

Source: Internet
Author: User

Java exception details
Exception description the exceptions in Java are some possible situations that may impede the current program running and cause program execution to fail, such as the Division by zero error in the program and the array subscript out of bounds. Exceptions are encapsulated into a class in Java and inherited fromThrowable, NamedExceptionIt has many sub-classes that describe many common exceptions in the system. The emergence of these exception mechanisms makes it especially convenient to handle some problems during programming, below are some simple usage cases. General Exception capture format

/*** Javac ExceptionDemo. javac * java ExceptionDemo * output: String index out of range: 3 */class ExceptionDemo {public static void main (String [] args) {try {// code that may generate exceptions should be placed in try System. out. println ("Hi ". charAt (3);} catch (Exception e) {// Exception handling System. out. println (e. getMessage ());}}}
When catchIn ExceptionChange StringIndexOutOfBoundsExceptionThe output result is String index out of range: 3Here: ExceptionYes StringIndexOutOfBoundsExceptionThe subclass object is assigned to the type of the parent class, which is called polymorphism in Java.
/*** Output: String index out of range: 3 */class ExceptionDemo {public static void main (String [] args) {try {// code that may generate exceptions should be placed in try System. out. println ("Hi ". charAt (3);} catch (StringIndexOutOfBoundsException e) {// System for exception handling. out. println (e. getMessage ());}}}
Abnormal inheritance relationships from ExceptionThe inheritance relationship diagram ExceptionThe relationship between the parent class and its subclass. The superclass is Throwable( ErrorAnd Exception), ThrowableIs Object(Directly or indirectly superclasses of all classes except Java itself ). To ExceptionThe classes at the end are inherited from Exception.

When tryMultiple exceptions may occur when multiple statements exist. Although the exception capture operation is added to the following code, no exception still occurs and the program crashes.
/*** Output: H * Exception in thread "main" java. lang. arithmeticException:/by zero * at ExceptionDemo3.main (ExceptionDemo3.java: 10) */class ExceptionDemo3 {public static void main (String [] args) {try {// code that may generate exceptions should be placed in try System. out. println ("Hi ". charAt (0); System. out. println (123/0);} catch (StringIndexOutOfBoundsException e) {// System for exception handling. out. println (e. getMessage ());}}}
The reason is that although catch is used to catch exceptions, only catch StringIndexOutOfBoundsExceptionException. This exception is only System.out.println("Hi".charAt(0));. While System.out.println(123 / 0);This statement produces another exception called ArithmeticExceptionThat is, the operation is abnormal. This exception does not have a corresponding capture statement, so the virtual machine uses the default processing method, that is, causing the program to crash. Add ArithmeticExceptionAfter an exception is captured, the exception can be handled as follows:
/*** Output: H * exception:/by zero */class ExceptionDemo3 {public static void main (String [] args) {try {// code that may generate exceptions should be placed in try System. out. println ("Hi ". charAt (0); System. out. println (123/0);} catch (StringIndexOutOfBoundsException e) {// System for exception handling. out. println (e. getMessage ();} catch (ArithmeticException e) {System. out. println ("exception:" + e. getMessage ());}}}
When there are a large number of statements in try, a lot of exceptions will occur. catch? Of course, you can use ExceptionTo receive all exceptions, but there will be problems, that is, all exceptions will be handled in a unified manner, then use ExceptionWhen mixed with other exceptions, pay attention to this situation, ExceptionMust be placed at the end catch. Otherwise, an error is reported during compilation. The correct syntax is as follows:
/*** Output: H * exception:/by zero */class ExceptionDemo3 {public static void main (String [] args) {try {// code that may generate exceptions should be placed in try System. out. println ("Hi ". charAt (0); System. out. println (123/0);} catch (StringIndexOutOfBoundsException e) {// System for exception handling. out. println (e. getMessage ();} catch (ArithmeticException e) {System. out. println ("exception:" + e. getMessage ();} catch (Exception e) {System. out. println (e. getMessage ());}}}
finallyAnother keyword in Java exception capture finally, Same catchThe usage is similar, finallyThere is no type, finallyThe function is as follows: try...catch...finallyA segment that must be executed. That is to say tryCode or no exceptions are generated in finally. This can be applied to some network operations. For example, when a database is opened and an error occurs during database operations finallyTo close the database. This avoids the system from opening many database connections, which cannot be closed and cannot be operated. This will consume a lot of system resources. The same is true when accessing the network. Some finallyThe demo is as follows:
/*** Output: * B * C */class ExceptionDemo4 {public static void main (String [] args) {try {int num = 4/0; // a System exception occurs. 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"); int num = 4/0; // make an Exception} catch (Exception e) {System. out. println ("B");} finally {System. out. println ("C") ;}}/ *** output: * 4*4*0 */class ExceptionDemo4 {public static void main (String [] args) {int num = 4; try {System. out. println (num); int n = 10/0; // manufacturing Exception num + = 2; // enter Exception Handling immediately after an Exception occurs} catch (Exception e) {System. out. println (num); num = 0;} finally {System. out. println (num );}}}
tryWhen an exception occurs during the execution of the Code in, the code will not continue to be executed, but will jump to the corresponding exception handling code segment for execution, and then execute finallySegment code. In a function with a return value, finallyThe execution is 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 () {int num = 4; try {System. out. println ("try:" + num); int n = 10/0; // manufacturing Exception} catch (Exception e) {System. out. println ("catch:" + num); return num;} finally {num ++; System. out. println ("finally:" + num);} return 0 ;}}
When finallyPreviously returnStatement, the content of the returned value is pushed to the stack. finallyModifying numWill not affect the final mainThe content of the returned value received by the function, which also reflects finallyIt will certainly be executed. However, when the following situations occur, it is necessary to choose from the following:
Import java. io. file; import java. io. fileOutputStream; import java. io. IOException;/*** file content: Hello * If the System. exit (0); comment out, the file content is Hi */class ExceptionDemo5 {public static void main (String [] args) {try {FileOutputStream fout = new FileOutputStream (new File ("E: \ ex.txt"); fout. write ("Hello ". getBytes (); fout. close (); System. exit (0); // exit the system directly} catch (IOException e) {} finally {try {FileOutputStream fout = new FileOutputStream (new File ("E: \ ex.txt "); fout. write ("Hi ". getBytes (); fout. close () ;}catch (IOException e ){}}}}
So finallyThe program must be established and then the program is still in the running state. The program can no longer be executed if it has been withdrawn from the virtual machine. finally. try...finallyCombination

Besidestry...catch...finallyThere is alsotry...finallyCombination method, that is, remove the catch segment. If the code segment throwsRuntimeExceptionThe exception is thrown to the previous layer.RuntimeExceptionOr its subclass will be compiled incorrectly. (ArithmeticExceptionBelongRuntimeException)

/*** 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 {int num = 6/0;} finally {System. out. println ("method: finally ");}}}
Exception throw throwsException Handling can be used try...catch, You can use try...catch...finally, You can also use try..finallyYou can also use other methods. throwsThrowing an exception to the previous layer refers mainFunction call methodMethod, methodMethod mainThe function is the last layer.
/*** Output: * main: Hello */class ExceptionDemo7 {public static void main (String [] args) {try {method ();} catch (ClassNotFoundException e) {System. out. println ("main:" + e. getMessage () ;}} public static void method () throws ClassNotFoundException {Class <?> C = Class. forName ("Hello ");}}
When multiple exceptions are thrown throwsLater use ,And throw an exception. throwAs follows:
/*** 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 () throws ClassNotFoundException, IllegalAccessException {// Class <?> C = Class. forName ("Hello"); throw (new IllegalAccessException ("-Message -"));}}
Custom exceptions: Custom exceptions are simple. You only need to inherit ExceptionOr inherit ExceptionSubclass, 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 () throws MyException {throw (new MyException ("My Exception "));}}
RuntimeExceptionIntroduction when throwing RuntimeExceptionOr RuntimeExceptionDoes not need to use throwsThis type of exception may not be well handled by capturing the method name. For example, even if an exception is caught when the Division by zero error occurs, the subsequent calculation results will be affected, an incorrect calculation result is displayed. As shown in the preceding zero division exception, you do not need to add the exception type 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 ()/* do not add ArithmeticException */{try {int num = 6/0;} finally {System. out. println ("method: finally ");}}}

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.