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
, NamedException
It 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
catch
In
Exception
Change
StringIndexOutOfBoundsException
The output result is
String index out of range: 3
Here:
Exception
Yes
StringIndexOutOfBoundsException
The 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
Exception
The inheritance relationship diagram
Exception
The relationship between the parent class and its subclass. The superclass is
Throwable
(
Error
And
Exception
),
Throwable
Is
Object
(Directly or indirectly superclasses of all classes except Java itself ). To
Exception
The classes at the end are inherited from
Exception
.
When
try
Multiple 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
StringIndexOutOfBoundsException
Exception. This exception is only
System.out.println("Hi".charAt(0));
. While
System.out.println(123 / 0);
This statement produces another exception called
ArithmeticException
That 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
ArithmeticException
After 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
Exception
To receive all exceptions, but there will be problems, that is, all exceptions will be handled in a unified manner, then use
Exception
When mixed with other exceptions, pay attention to this situation,
Exception
Must 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 ());}}}
finally
Another keyword in Java exception capture
finally
, Same
catch
The usage is similar,
finally
There is no type,
finally
The function is as follows:
try...catch...finally
A segment that must be executed. That is to say
try
Code 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
finally
To 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
finally
The 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 );}}}
try
When 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
finally
Segment code. In a function with a return value,
finally
The 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
finally
Previously
return
Statement, the content of the returned value is pushed to the stack.
finally
Modifying
num
Will not affect the final
main
The content of the returned value received by the function, which also reflects
finally
It 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
finally
The 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...finally
Combination
Besidestry...catch...finally
There is alsotry...finally
Combination method, that is, remove the catch segment. If the code segment throwsRuntimeException
The exception is thrown to the previous layer.RuntimeException
Or its subclass will be compiled incorrectly. (ArithmeticException
BelongRuntimeException
)
/*** 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
throws
Exception Handling can be used
try...catch
, You can use
try...catch...finally
, You can also use
try..finally
You can also use other methods.
throws
Throwing an exception to the previous layer refers
main
Function call
method
Method,
method
Method
main
The 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
throws
Later use
,
And throw an exception.
throw
As 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
Exception
Or inherit
Exception
Subclass, 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 "));}}
RuntimeException
Introduction when throwing
RuntimeException
Or
RuntimeException
Does not need to use
throws
This 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.