exception handling mechanism for Java The exception handling code in the program can be separated from normal business code to ensure that the program code is more elegant and can improve the robustness of the program.
In try{} catch () {} exception handling mechanism, the exception object of a try will be committed to the Java environment, called throwing an exception, the runtime will look for the catch block to handle the exception, if found, is called catch exception, if not found the appropriate catch, The runtime environment terminates and the program terminates
Error and Exception:
Java divides all non-normal situations into two types, error (Errors) and exception (exceptions), and they all inherit the Throwable parent class. Error errors generally refer to virtual machine-related errors, such as system crashes, virtual machine errors, dynamic link failures, and so on, which cannot be recovered or not captured, will cause the program to break, so you should not catch errors with catches, and do not need to throw an error with throws
Multiple exception captures and finally statement blocks
/* * When the runtime assigns a value to the args parameter of the main method, right-click--run as--run config--agument--Parameter Enter parameter *//* * Exception handling syntax structure, the TRY statement block is required, and the catch finally must have one */public Class Subexceptiontest{public static void Main (string[] args) {Try{int a = Integer.parseint (args[0]); int B = Integer.parse Int (args[1]); int c = A/b; SYSTEM.OUT.PRINTLN ("The result of dividing two numbers is:" +c);} /* * Java 7 starts with new methods, one catch can capture multiple exceptions at the same time * Each exception is default to the final decoration, so it cannot be re-assigned */catch (Indexoutofboundsexception | NumberFormatException | ArithmeticException e) //Catch the subclass exception before capturing the parent class exception, or compile the error {e.printstacktrace (); return; 1 ..... The finally statement block is executed//system.exit (0); 2: Exit the virtual machine, the finally statement is not executed//e = new RuntimeException (); } catch (Exception e) {e.printstacktrace (); e = new RuntimeException (); Capturing an exception individually can be re-assigned, the exception variable has no final modifier} finally{system.out.println ("Primarily for physical resource recycling");}}}
Do not use Return,throw in a finally statement block that will cause the method to terminate, once used, will invalidate the return throw in the try Catch
/* Usually do not execute the return throw statement in the finally block, otherwise it will invalidate the return throw in the try catch, * the following program: * When running to a return statement in a try does not immediately cause the method to end, Instead, find out if there is a finally block, and if there is, * then execute the return in the try after executing finally, and if there is a return statement in Finally, no return in the try will be executed to invalidate the return in the try */public Class Returntest{public static void Main (string[] args) {Boolean a = Test (); System.out.println (a); Output False}public static Boolean test () {Try{return true;} Finally{return false;}}}
JAVA7 Automaticclose the resource's try statement
Import java.io.*;/* * The resource requested in the Try statement is automatically closed, provided the resource class implements the Autocloseable, or Closeable interface, which defines the close () method. * In Java7 almost all resource classes have implemented the above two interfaces * automatically shut down the resource's try statement, equivalent to contain the implicit finally statement block, so there can be no catch. Finally statement block */public class autoclosetest{public static void Main (string[] args) throws Ioexception{try (BufferedReader br = New BufferedReader (New FileReader ("D:\\b.txt")); PrintStream PR = new PrintStream (New FileOutputStream ("D:\\a.txt"))) {System.out.println (Br.readline ()); Pr.println ("I am a good person"); } /*catch (IOException e) {e.printstacktrace ();} */}}
Checked and runtime anomalies
/* * 1. Exception is divided into checked exception, runtime exception, as long as not runtimeexception itself or subclass, all belong to checked exception * 2.Checked exception is Java unique, It considers all checked exceptions to be able to be repaired or handled, so it must be shown that handling exceptions or throws throws exceptions * cannot be compiled without processing, which increases the rigor and robustness of the program, but also increases the complexity of the program * 3. If a method throws a checked exception, the method that calls it must handle the exception or throw the exception again, eventually handing the exception the way the JVM,JVM handles the error by printing the exception's * Trace stack information, and terminating the program *//* * Throws method is used only for method signatures, When a subclass method overrides a method that the parent class throws an exception, it should follow two principles * 1. The exception class that the subclass throws can only be the parent class itself or its subclass * 2. Subclasses cannot throw more exceptions than the parent class *//* * Recommended runtime exception, which can ensure the correct code and error handling separation, ensure the robustness of the program, It also avoids the tedious nature of programming *//* * Self-throwing exceptions using the Throw keyword, only one exception instance can be thrown at a time * When Java receives the exception that the program throws itself, it also terminates the current execution stream and goes to the corresponding catch, which is the same as the programmer throws the exception manually * If the throw throws a checked exception, then it must be shown that the exception is caught or the declaration throws an exception, and so is the caller of the call * if the throw is runtimeexception, then there is no such requirement, whether it is handled, whether the throw is not related */public class Checkedandruntime{public static void Main (string[] args) {//runtime (); When the exception needs to be handled by the JVM, the following code cannot be executed, but runtime () can be executed after the Try{check ();} catch (Exception e) {e.printstacktrace ();}} public static void Check () throws exception{System.out.println ("test"); throw new Exception ("Throw checked exception"); public static void Runtime () {throw new RuntimeException ("Throw runtime Exception");}}
Custom Exception classes:
/* Custom checked exception, only need to inherit exception base class, and custom runtime exception, need to inherit runtimeexception * All need to provide two constructors, one without parameter, and one string as parameter, this parameter is GetMessage ( The return value of */public class Identityexception extends Exception{public identityexception () {}public identityexception (String Message) {super (message);}}
catch and throw Simultaneous use
/* In the current method in which the exception occurs, the program only partially processes the method, and the other means to call it to process * complete multiple methods to collaborate on an exception, using catch and throw *//* * used in enterprise-class applications, the use of the combination is very common, The catch is used as a background for logging exception information * Throw is used to provide the user with a hint message */public class Catchandthrow{public static void Main (string[] args) {try{bid (" 3n ");} catch (Exception e) {e.printstacktrace ();}} public static void Bid (String bidprice) throws exception{double d = 0.0;//Auction Price try{double.parsedouble (bidprice);} catch (Exception e) {e.printstacktrace (); throw new Exception ("Bid price must be numeric"); The code after//throws will not be executed */* * If the exception is not automatically thrown, the subsequent code will be executed * Throw will end the operation of the method, which is also the reason why the throw is not used in the finally block */}system.out.println ("test can execute"); Not executed}}
JAVA7-EnhancedThrow Statement:
Import Java.io.fileoutputstream;import java.io.ioexception;/* * Before the exception thrown in the catch is Exception,java7, the main function can only throw exception * However, the method may only be thrown ioexception,java7 will examine it more carefully, allowing more accurate subclasses to be thrown */public class Java7exception{public static void Main (string[] args) Throws IOException//throws exception subclass {Try{new FileOutputStream ("A.txt");} catch (Exception e) {e.printstacktrace (); throw e;}}}
Exception Chain:
Import java.sql.sqlexception;/* * In peacetime application development, such as the use of three-tier architecture, the business logic layer access to the persistence layer SQLException should not be passed to the user interface * but should prompt closer to the user's information, that is, capturing the original exception, Throws a new exception, becomes an exception translator */public class linkexception{//payroll settlement Public Double Calsal () {try{//Achieve Payroll settlement}catch (SQLException e) {// Record the original information ...//the information that prompts the user//throw new Saxexception ("Database access exception");/* Saves the original exception, the chain of responsibility mode * requires saxexception with the corresponding constructor saxexception (Throwable e) */throw new Saxexception (e);}}
Java'sException Tracking Stack:
/* * Exception passed to JVM,JVM print out exception trace stack information, * Exception in thread "main" java.lang.RuntimeException: Exception at Stackexception.two ( STACKEXCEPTION.JAVA:15) at Stackexception.one (stackexception.java:11) at Stackexception.main (StackException.java:7 the most external usually is main () or run () can clearly see the exception of the passing of the exception stack! Exactly the opposite of the method call stack */public class Stackexception{public static void Main (string[] args) {one ();} public static void One () {one ()}; public static void () {throw new RuntimeException ("Exception");}}
Note:
The exception handling mechanism is designed to separate unexpected exception handling code from normal business logic, so never use exception handling instead of normal business judgments
1> don't confuse anomalies with common mistakes
2> do not use exceptions to replace process Control
3> do not use an overly large try statement block
4> Avoid using catch all
5> do not ignore the caught exception
Exception Handling for Java basics