Java's exception mechanism relies mainly on the try, catch, finally, throw and throws five keyword, in which the code block (curly brace) immediately following a curly brace is not omitted, abbreviated as a try block. It puts the code that might throw an exception.
The corresponding exception type and a block of code after the catch. A block of code that indicates that the catch block is used to handle such a type. Multiple catch blocks can also be followed by a finally block, finally blocks are used to reclaim the physical resources opened in the try block, and the exception mechanism guarantees that the finally block is always run. Throwskeyword is mainly used in method signatures, throws a detailed exception object, and throw is used to throw an actual exception, throw can be used as a statement, throw a detailed exception object.
We want all errors to be discovered during the compile phase, that is, to exclude all errors before attempting to execute the program, but this is unrealistic and the remaining issues must be resolved during execution.
Java divides the exception into two types. Checked exceptions and runtime exceptions, Java feels that checked exceptions are exceptions that can be handled during the compile phase. So he forces the program to handle all checked exceptions. The runtime exception does not need to be processed.
Java's exception handling mechanism can make the program have excellent fault tolerance and make the program more robust.
When the program executes an unexpected situation. The system proactively generates a exception object to notify the program, which separates the "Business function implementation Code" and "error handling code". Provides better readability.
Here's how I learned about the exception mechanism in crazy Java handouts. Summarize and learn together.
1, assume that the execution of the business logic code in the try block when an exception occurs, the system itself to generate an exception object. The exception object is presented to the Java execution Environment, a process known as throw (throw) exceptions.
When a program enters a catch block that is responsible for exception handling, the system-generated exception object is passed to the exception shape after the catch block, allowing the catch block to obtain specific information about the exception through the object.
try{
Business Implementation Code
`````````````
}
catch (Exception e)
{
Alert input Not valid
}
2, for the exception capture, it is important to remember to catch small anomalies, and then catch large anomalies. Because the runtimeexception already includes NullPointerException, the catch block at ② will never get the chance to run.
public class Nulltest {
public static void Main (string[] args) {
Date D=null;
try{
System.out.println (D.after (New Date ()));
}catch (RuntimeException e) {①//will error
System.out.println ("Exception at execution time");
}catch (NullPointerException ne) {②
SYSTEM.OUT.PRINTLN ("null pointer exception");
}
}
}
3, when capturing multiple types of exceptions, the exception variable has an implicit final modification, so the program does not, um, can assign another value to the exception variable. When capturing a type of exception, the exception variable does not have a final decoration.
public class Multiexceptiontest {
public static void Main (string[] args) {
try{
int A=integer.parseint (args[0]);
int B=integer.parseint (args[1]);
int c=a/b;
SYSTEM.OUT.PRINTLN ("The result of dividing the two numbers you entered is:" +c);
}catch (Indexoutofboundsexception | NumberFormatException | ArithmeticException IE) {
SYSTEM.OUT.PRINTLN ("A program has an array out of bounds, a number format exception, an arithmetic exception of one");
When capturing multiple exceptions, the exception variable defaults to the final decoration, so the following code is an error.
Ie=new arithmeticexception ("test");
}catch (Exception e) {
System.out.println ("Unknown exception");
When capturing a type of exception, the exception variable does not have a final decoration. So the following code is completely correct.
E=new runtimeexception ("test");
}
}
}
4. The garbage collection mechanism of Java does not reclaim any physical resources, and the garbage collection mechanism can only reclaim memory occupied by objects in heap memory. In order to ensure that the material resources opened in the try block can be reclaimed, the exception handling mechanism provides a finally block. Regardless of whether the code in the try block is an exception or not, whichever catch block is run. The return statement is even run in a try block or catch block. Finally blocks are always run.
However, assuming that the System.exit (1) statement is used to exit the virtual machine in the exception handling code, the finally block will lose the run opportunity.
public class Finallytest {
public static void Main (string[] args) {
FileInputStream Fis=null;
try{
Fis=new FileInputStream ("A.txt");
}catch (IOException IoE) {
System.out.println (Ioe.getmessage ());
Ioe.printstacktrace (); The trace stack information for this exception is output to the standard error output.
Return Although the return statement forces the method to end, the code in the finally block must be run first.
System.exit (1); Assume that you use the System.exit (1) statement to eject a virtual machine in exception handling code. Then the finally statement loses the chance to run.
}finally{
if (fis!=null) {
try{
Fis.close ();
}catch (IOException IoE) {
Ioe.printstacktrace ();
}
}
SYSTEM.OUT.PRINTLN ("Resource recycling in the run finally block!")
");
}
}
}
public class finallyflowtest {
public static void Main (string[] args) throws exception{
boolean a=test ();
System.out.println (a);
}
< /span>public static Boolean test () {
try{
return true;
}finally{
return false;
}
}
}
6, the idea of throwing an exception using the throws declaration is that the current method does not know how to handle such a type of exception, the exception should be handled by the caller at the top level, assuming that the main method does not know how to handle such a type of exception, but also can use the throws declaration to throw an exception. The exception is given to the JVM for processing. The JVM handles exceptions by printing the trace stack information for the exception. and terminates the execution of the program.
Once the exception is thrown using the throws statement declaration, the program does not need to use the Try...catch block to catch the exception.
There is a limitation when using the throws declaration to throw an exception. is a rule in "two small" when the method is overridden: A subclass method declaration throws an exception type that should be a subclass of the exception type thrown by the parent class method declaration or the same. A subclass method declaration throws an exception that does not agree to be more than the exception thrown by the parent class method declaration.
7, the throw statement is not an exception class, but an exception instance, and can only throw an exception instance at a time.
Assume that the throw statement throws an exception when the checked exception occurs. The throw statement is either in the try block, the display captures the exception, or is placed in a method with the throws declaration thrown. That is, the exception is given to the caller of the method for processing. Assuming that the exception thrown by the throw statement is a runtime exception, the statement does not need to be placed in a try block, or in a method with a throws declaration thrown, and the program can display the use of try: Catch to catch and handle the exception, and to ignore the exception, handing the exception to the method caller.
public class ThrowTest { Span style= "White-space:pre" >
public static void Main (string[] args ) throws exception{
/*try{
//Invoke declares a method that throws a checked exception. Either the display captures the exception, or the
throwchecked (3) is declared again in the main method;
}
catch (Exception e) {
System.out.println (E.getmessage ());
}*/
// The call declares the method that throws the runtime exception to show that the exception is caught. You can also ignore the exception.
Throwruntime (3);
Throwchecked (3);
}
public static void throwchecked (int a) throws exception{
if (a>0) {
throw new Exception ("A has a value greater than 0, does not meet the requirements");
}
}
public static void Throwruntime (int a) {
if (a>0) {
throw new RuntimeException ("A has a value greater than 0, does not meet the requirements");
}
}
}
8. If an exception is caught and handled within the method in which the exception occurred, the caller of the method will not be able to catch the exception again.
The method signature declares that an exception is thrown, giving the exception to the method caller for processing.
In order to achieve such a situation in which multiple methods work together to handle the same exception, the throw statement can be combined in the catch block to complete.
public class Auctiontest {
Private double initprice = 30.0;
public void Bid (String bidprice) throws auctionexception{
Double d=0.0;
try{
D=double.parsedouble (Bidprice);
}catch (Exception e) {
E.printstacktrace ();
throw new Auctionexception ("Bid price must be numeric and cannot include other characters!") ");
}
if (Initprice > D) {
throw new Auctionexception ("Bid price is lower than the auction price, do not agree to bid!") ");
}
Initprice=d;
}
public static void Main (string[] args) {
Auctiontest at=new auctiontest ();
try{
At.bid ("DF");
}catch (Auctionexception ae) {
System.err.println (Ae.getmessage ());
}
}
}
9. When an object-oriented application executes, a series of method calls are often taken to form a "method call stack." Exception propagation is the opposite: only the exception is not completely captured (the exception is not captured, or the exception is processed and the new exception is run again). The exception from the way the exception occurred gradually spread out, first passed to the caller of the method, the method is low, the user again to its caller.
。
。
Until it is finally uploaded to the main method, assume that the main method still does not handle the exception. The JVM will abort the program. and print the exception tracking stack information.
10. The original intention of exception handling mechanism trial teaching the processing code of unexpected exception and normal business logic processing code separation. Therefore, you should never use exception handling to replace normal business logic inference.
The efficiency of the anomaly mechanism is worse than the normal process control, so do not use exception handling to replace normal program flow control.
Java Exception handling mechanism