--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
catch
In the
Exception
Into
StringIndexOutOfBoundsException
, the output is also
String index out of range: 3
, as follows: here
Exception
Is
StringIndexOutOfBoundsException
The 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
Exception
The inheritance diagram can be clearly known
Exception
The relationship of the parent class and its subclasses, the superclass is
Throwable
(
Error
And
Exception
of the common superclass),
Throwable
The Super class is
Object
(except for the direct or indirect superclass of all classes in Java outside of itself). To
Exception
The end class is inherited from the
Exception
。
When
try
When 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
StringIndexOutOfBoundsException
Exception, 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
ArithmeticException
Exceptions 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
Exception
To receive all exceptions, but then there is the problem that all exceptions will be handled uniformly, so use
Exception
and other anomalies mixed with the situation, this situation should be noted,
Exception
Be 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 ()); } }}
finally
Another keyword in the keyword Java exception capture
finally
With
catch
is similar in usage, but
finally
After no type,
finally
The function is as
try...catch...finally
The inevitable implementation of the paragraph. Other words
try
The code inside is either generating or not producing an exception and will eventually execute
finally
Within 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
finally
Writing 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
finally
The 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); } }}
try
The code inside does not continue executing when it encounters an exception, but instead jumps to the corresponding exception-handling code snippet and executes
finally
The code for the segment. In a function with a return value,
finally
is 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
finally
It's been there before.
return
Statement, the contents of the returned value are pushed to the stack, so the
finally
Modified in
num
The value is not affected by the final
main
function to receive the contents of the return value, which also reflects the
finally
Will 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
finally
The 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
finally
The content of the.
try...finally
Combination
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
throws
For exception handling, you can use the
try...catch
, you can use
try...catch...finally
, you can also use
try..finally
And of course there are other ways that you can use
throws
Throw an exception to the upper layer, where the previous layer refers to the
main
Function call
method
Method, for
method
Method for
main
The 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
throws
Later use
,
, and throwing an exception is used
throw
To 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
Exception
Can, or inherit
Exception
Sub-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")); }}
RuntimeException
Introduction when thrown
RuntimeException
Or
RuntimeException
Sub-class without using the
throws
After 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