Getting started with java-exception capture and processing
in
languages that do not have exception handling, it is often necessary to have a large number of judgment statements that match the thought of errors to capture all possible errors in the Program. Make full use of Java exception handling mechanism to improve the stability and efficiency of the Program.
Exception handling mechanism for Java
- Once an exception is generated, an instantiated object of the exception class is generated First.
- This exception object is captured in a try Statement.
- The resulting exception object matches the individual exception types in the Catch statement and executes the code in the catch statement if the match succeeds.
- Finaly is the exception of the unified export, will be Executed.
All subclass instances can be received by the parent class, and with the concept of upward transformation, all exception objects can be received using the exception class
Throws keywords
Throws: a method declared with throws means that this method does not handle exceptions and is handled at the call of the Method.
Do not use the throws keyword in the main method.
throw keyword
You can use the Throw keyword to throw an exception artificially, throwing an instantiated object of the exception class Directly.
Example: application of throw and throws
Designing a division method requires that the "calculate start" information, the "calculate end" information must be printed, and if there is an exception, the call is invoked for Processing.
1 packageSep18;2 /*Designing a division method requires that the "calculate start" information, the "calculate end" information must be printed, and if there is an exception, the call is invoked for Processing. 3 */4 public classTrowDemo02 {5 public Static voidmain (String Args[]) {6Math m=NewMath ();7 Try{8System.out.println ("division operation:" +m.div (10, 0));9}Catch(Exception E) {TenSystem.out.println ("abnormal generation:" +e);//executes when an exception is Generated. one } a } - } - classmath{ the public intDivintIintJthrowsexception{//method can not handle exceptions, throw directly -SYSTEM.OUT.PRINTLN ("calculate Start * * * * * * * * * *); - intTemp=0; - Try{ +temp=i/j; -}Catch(Exception E) {//Catching exceptions + ThrowE//to give the abnormal structure to the transferred use a}finally{ atSYSTEM.OUT.PRINTLN ("* * * * Calculation End * * * *"); - } - returntemp; - } -}
Calculation start ******** calculation end ** */by Zero
Exception class and RuntimeException class
The RuntimeException class is a subclass of the exception class, but it can be throws directly without the try---catch---thrown, but it is best to catch it normally.
Getting started with java-exception capture and processing