As a programmer for object-oriented programming, you must be familiar with the following sentence:
Copy Code
Try
{
code block
}
catch (Exception e)
{
Exception handling
}
Finally
{
clean-up work
}
Copy Code
Is the most common object-oriented exception handler, and even we will inexplicably be required by the compiler to add this module, and even we do not know how to catch the exception of how to deal with ...
Why should there be an anomaly
In fact, this problem needless to say, programmers know, simply summed up as a sentence: To enhance the robustness of the program chant, such as the following code:
Class Denominatorzeroexception extends exception{}
Public Double Division (int numerator,int denominator) throws Denominatorzeroexception
{
Double result;
Try
{
if (denominator = 0)
throw new Denominatorzeroexception ();
Else
result = Numerator/denominator;
}
catch (Denominatorzeroexception e)
{
E.printstacktrace ();
return-1;
}
return result;
This code is simple, in order to prevent a denominator of 0 in division, in order to enhance the robustness of the code, I declare a custom exception named: Denominatorzeroexception, this exception inherits from all the root class exception of the exception, When the code finds that the denominator is 0, the new exception is then run out, and when the catch catches the exception, a predefined flag-1 is returned, otherwise the division result is returned normally.
In fact, in the Java language, in accordance with my own reading and normal programming understanding, the role of the exception can be summed up as follows two points:
Enhance the robustness of the program. When an exception is encountered (why is it called an exception instead of an error), that is, in the current programming environment, this situation is very strange, not normal, can not be solved we could capture it, then have two choices: first, just like the code above, we know the cause of the exception, and then do the appropriate processing, This does not affect the normal execution of the program; second, we do not know what to do with capturing this exception, we can use the exception chain of Java to throw this exception to the upper level of code or directly to the console (like the code e.printstacktrace above) Print out the stack trajectory or use the exception description to add to the main function entrance).
Report. Java programmers may find that when our program encounters a bug stop, all reported error messages are generated in the form of an exception, which allows programmers to write programs without having to think about what to do if a program runs wrong, Java will do it, and errors will be reported to you and will never be omitted ( In addition to the exception "swallowing", later on, the programmer can focus on the design and implementation of their own code.
throw keyword
We need to throw the keyword when we run an exception, but in a way we can make an analogy between throw and return, because when we throw an exception using throw, we jump out of the current method or scope, which is very similar to return. But it must not be confusing, because the return keyword returns "location" is usually the main function where throw throws an exception, and the "location" that catches the exception may be far away from the address of an existing function.
Class Denominatorzeroexception extends exception{}
Class Anotherexception extends Exception
{
Public Anotherexception (String s) {super (s);}
}
Public Double Division (int numerator,int denominator) throws Denominatorzeroexception, Anotherexception
{
Double result;
Try
{
if (denominator = 0)
throw new Denominatorzeroexception ();
Else
result = Numerator/denominator;
}
catch (Denominatorzeroexception e)
{
Throw e;
/* OR * *
throw new RuntimeException (e);
/* OR * *
Anotherexception AE = new Anotherexception ("from Division");
Ae.initcause (New Denominatorzeroexception ());
Throw AE;
}
return result;
}
Or the above example of Division, I would like to make a point:
When we caught an exception in the catch and didn't know how to handle it, we can use throw to throw the exception directly;
Also we can throw this exception directly to RuntimeException, let it throw the Run-time exception directly (that is, the reality of the console error message);
However, one of the problems with the above two ways is that when we throw the exception again, we lose the position where the first exception occurred, so we used Initcause to join the original exception and added "from division" to the exception information.
Interpretation of the exception "swallowed", is to catch the exception to do nothing, nor throw, then this is very dangerous, because the error message can not be found.
Exception description throws
We certainly encounter this when invoking Java library functions (especially where IO operates): Calling a function, and then the compiler complains that the solution is either to join the Try,catch block or to add throws to the back of the calling function. and follow the exception that may be thrown. Here the latter is the so-called anomaly description.
Why should there be an exception description: This is primarily the programmer who writes the class to inform the client programmer of the exceptions that might be thrown by the method.
Format: Method name () throws list of all potential exception types
The exception description divides the exceptions in Java into two categories, one being the checked exception, the exception and all the exceptions inherited from it, and the other being an unchecked exception, the RuntimeException, the run-time exception. How do you understand it?
To put it bluntly, the exception that is checked is that if you use the throw to throw an exception in a function or that the function you call uses the throw to throw an exception, then you must add the throws keyword after the function and list all the exceptions that may be thrown later; The exception that is not checked is that you do not have to make a special statement when you throw it, as in the case of division above.
This top-down constraint ensures that the Java code is at a certain level of abnormal correctness. But it's controversial, some people think it's good, but some people think it's going to affect programmer efficiency, because sometimes you don't know what you're catching or what to do with it, but the compiler will force you to add these modules.
finally keyword
Finally keyword Common Database buddies certainly understand, generally we in finally to close the database connection or do some cleanup work. About finally I want to say two interesting things:
First, to ensure the completion of the task
Why did you say that? finally keyword, because no matter what command is executed in the Try statement, finally the statement block is bound to execute (this ensures that some of the necessary cleanup work), such as:
public class Multiplereturns
{
public static void f (int i)
{
SYSTEM.OUT.PRINTLN ("Initialization that requires cleanup");
Try
{
System.out.println ("point 1");
if (i = = 1)
Return
System.out.println ("point 2");
if (i = = 2)
Return
System.out.println ("point 3");
if (i = = 3)
Return
System.out.println ("End");
Return
}
Finally
{
System.out.println ("performing cleanup");
}
}
public static void Main (string[] args)
{
for (int i = 1; I <= 4; i++)
f (i);
}
}
Everyone executing this code would be surprised to find that even if the code in a try calls the return command, finally, it must be executed.
Second, nested try
public class Cleanup
{
public static void Main (string[] args)
{
Try
{
Inputfile in = new Inputfile ("Cleanup.java");
Try
{
String s;
int i = 1;
while ((s = in.getline ())!= null)
; Perform line-by-line processing ...
}
catch (Exception e)
{
System.out.println ("Caught Exception in Main");
E.printstacktrace (System.out);
}
Finally
{
In.dispose ()//Custom
}
}
catch (Exception e)
{
SYSTEM.OUT.PRINTLN ("Inputfile construction failed");
}
}
} /*
* Output:dispose () successful
*/// :~
Copy Code
For this example, we see that we're creating a Inputfile object that needs to be cleaned up with the Dispose method when we successfully create it, but we don't need to clean it up if it fails. If only one does not use nested try blocks, then finally it will be executed anyway. So to avoid this, the above nested try statement works.