Hacker programmer's java exception understanding

Source: Internet
Author: User

Exceptions The existing program development technology and testing technology cannot ensure that there are no errors in the program. Many errors do not occur during program compilation (that is, code errors ), it is generated at runtime due to various reasons (the network is suddenly disconnected and the file does not exist. Several conceptual compilation errors: the syntax check in the compilation phase. The code writing does not meet the syntax rules. Runtime error: Incorrect Command Execution condition and Semantic Error. Logical error: failed to get expected results because the design does not meet the requirements. Exception: an error occurs when the program is running. (The concept of runtime errors here refers to errors that occur during the runtime, which is different from the scope covered by the java RuntimeException class. The latter is only a subset of the former) exception classification: (Java provides the Throwable class. Only the Throwable class or its subclass objects can be thrown by virtual machines or throw statements and captured by catch statements. The Throwable class has two subclasses: error and Exception indicate different levels of exceptions.) Error: a serious catastrophic Error (which cannot be captured or reported ). For example, OutOfMemoryError (insufficient memory), ThreadDeath, IOError, and LinkageError (Library Link error. When these exceptions occur, the JVM generally terminates the thread. Exception: exceptions that the program can handle (captured ). There are two types of runtime exceptions: The RuntimeException class and its subclass exceptions. Exceptions thrown during normal JVM operations do not need to be declared in advance. Not captured, JVM will take over (RuntimeExceptionand its subclasses are uncheckedexceptions. unchecked exceptions donotneed to be declared in a method or constructor 'sthrowsclause if they can be thrown by the execution of the method orconstructor and propagate outside the method or constructorboundary .) for example, ArithmeticException (arithmetic exception), BufferOverflowException (buffer benefit), BufferUnderflowException, and NullPointerException (NULL pointer ). Non-runtime exception: exception other than RuntimeException. The catch clause or throws clause must be used to specify the exception that may be thrown. Otherwise, the compilation fails. For example, IOException (IO exception), AWTException (AWT exception), InterruptedException (Interrupt exception), and TimeoutException (supermarket exception) are written on others' blogs, it feels good: (when an exception occurs during runtime, the system will throw the exception to the upper layer and always encounter code processing. If there is no processing block, to the top layer, Thread. run () will throw the Thread if it is a multi-Thread, and main () will throw the Thread if it is a single Thread. If the thread is thrown, the thread exits. If the exception is thrown by the main program, the entire program will exit. Exception during running is a subclass of Exception. It also has common exceptions and can be processed by Catch blocks. But we often don't handle it. That is to say, if you do not handle runtime exceptions, after a runtime exception occurs, either the thread is terminated or the main program is terminated. If you do not want to terminate, you must capture all running exceptions and never let the processing thread exit. The exception data appears in the queue. The normal processing should be to discard the exception data and then record the log. Normal data cannot be processed due to abnormal data. Such processing in this scenario may be a good application, but it does not mean that you should do so in all scenarios. If you encounter some errors in other scenarios, If you exit the program well, you can ignore the runtime exception or exit by explicitly controlling the program through Exception Handling .) Java Exception Handling Mechanism java processes various errors in running programs into "exception objects" and throws them out of the refrigerator. Capture and process this exception object. The processing policy is as follows: processing or declarative processing: Use the try-catch mechanism. Use try to monitor code segments that may encounter exceptions and use catch to catch and handle exceptions. Declaration: declare that you do not handle the exceptions yourself, throwing an exception object to its caller is implemented using the throws mechanism (in the method declaration section, throws is used to specify the exceptions that may be thrown by this method to remind the caller to take appropriate measures) (with the support of JVM, java exception handling is very different from traditional processing methods. The Virtual Machine needs to translate bytecode into binary code before execution, and then execute it. JVM can predict the execution effect based on the current situation before execution. If an exception occurs, the VM creates an exception object and throws the object.) JVM working mode: the monitoring mode and normal mode. JVM predicts the execution result to some extent, which affects the code execution efficiency, therefore, JVM only implements monitoring and prediction modes for the try-catch-finally statement and the code segment marked by throws. In normal mode, errors can only be captured and processed by the Java Virtual Machine (for example, Error and non-captured runtime exceptions). The JVM operation will be terminated) and throw format return type method name (parameter list) throws exception list {method body} reference instance of the throw exception object [java] import java. io. IOException; import java. util. role; public class Test {/*** @ param args */public static void main (String [] args) {// TODO Auto-generated method stub try {f ();} catch (ArrayIndexOutOfBoundsException e) {// TODO Auto-generated catch block Sys Tem. out. println ("array subscript out-of-bounds exception");} catch (ArithmeticException e) {// TODO: handle exception System. out. println ("arithmetic Exception");} catch (exception e) {// TODO: handle Exception System. out. println (e. getMessage () + "Exception") ;}} public static void f () throws ArithmeticException, ArrayIndexOutOfBoundsException, Exception {int [] x = {1, 2}; int y, z; while (true) {System. out. print ("enter an integer,-1 indicates the end:"); sums in = new sums (S) Ystem. in); y = in. nextInt (); if (y =-1) break; if (y = 2) throw new IOException (); // if no Exception is declared, here we will see the compilation error z = x [y]/y ;}} for the Exception Propagation Section Code: [java] public class Test {public static void main (String [] args) {a () ;}static void a () {B () ;}static void B () {c () ;} static void c () {int I = 5/0 ;}} running result: Exception in thread "main" java. lang. arithmeticException:/by zero at test. test. c (Test. java: 36) at test. Test. B (Test. java: 33) at test. test. a (Test. java: 30) at test. test. main (Test. java: 27) method calling sequence: main → a → B → c exception passing sequence: c → B → a → main → JVM (JVM termination) arithmeticException is a runtime exception and does not need to be captured. Note: 1. when the try block contains a return statement, finally will also execute [java] int f () {try {return 5 ;}finally {return 10 ;}} // This method returns 10 2. throw has a powerful turning function similar to return, that is, the statement after throw is not executed, and compilation fails. 3. in the rewrite method, www.2cto.com [java] class A {// if the two exceptions are changed, an exception in class B cannot be compatible with void f () in class () throws Exception {}} class B extends A {// that is, the Exception in this method must be the same as that in the preceding method or its subclass void f () throws IOException {}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.