Java in-depth understanding of the anomalies

Source: Internet
Author: User
Tags try catch

The basic idea of Java is that "poorly structured code cannot run"

Why use exceptions?

The first thing we can make clear is that the exception handling mechanism can ensure the robustness of our program and increase the availability of the system.

。 Exception is not a program syntax error, exception, is in the normal syntax of the code to run a situation such as what the building said, if the exception is not handled, the program is directly over, the reason for catching the exception is that you can have the opportunity to remedy the error.

Exception Definition : An exception condition is an issue that prevents the current method or scope from continuing to execute. It is important to be clear here: The exception code a certain degree of error, although Java has an exception handling mechanism, but we can not be "normal" view of the exception, the exception handling mechanism is to tell you: here may or has produced an error, your program is abnormal situation, May cause the program to fail!

So when will the anomaly occur? only in your current environment, the program will not function properly, that is, the program has not been able to solve the problem correctly, then it would jump out of the current environment, and throw an exception. After throwing an exception, it will first do a few things. First, it uses new to create an exception object, then terminates the program at the point where the exception was generated, and pops a reference to the exception object from the current environment. The exception handling mechanism takes over the program and starts looking for an appropriate place to continue executing the program, and the proper place is the exception handler, whose task is to recover the program from the wrong state so that the program either executes in a different way or continues execution.


The purpose of developing exception handling is to make it easier for programmers to handle errors, and the important principle of exception handling is to catch exceptions only if you know how to handle them. The important goal is to separate the error-handling code from the place where the error occurred, so that you can focus on what you want to accomplish, and the error handling, which is done in another piece of code.



1, there are only two ways to throw exceptions in Java: Throw display thrown, automatic throw (run-time exception).
    • Show Throw Exception : Exceptions in Java generally need to be displayed through the Throw keyword, but it cannot be used alone and needs to be used in conjunction with try...catch/finally or throws. (try cannot be used alone, it must be combined with catch or finally)
     
Class Simpleexception extends exception{}//custom exception class   try {  throw new simpleexception ();} catch (Exception e) {  E.printstacktrace (); }

or
public static void Main (string[] args) throws Simpleexception {throw new simpleexception ();  }

These two methods ofdifferent points are: Try (Detect exception code block) ... catch (handle exception) is the program (catch) handled the exception, the program runs normally, does not exit.and throws is just an exception, just tell the client programmer who is using this method that the method may throw exceptions, which allows the caller to know exactly what code is written to catch all potential exceptions. Java provides the appropriate syntax (and enforces the use of this syntax), which is a polite way for you to tell a client programmer what type of exception a method might throw, and then the client programmer can handle it accordingly. It is simply an exception description, stating the type of exception that might be thrown and not throwing an exception. This exception is expected to be handled by the caller. the code in the method generates an exception and is not processed, and the compiler will find the problem and remind you that either the handle (try catch) or the exception description indicates that the method will produce an exception (throws).
    • Automatically throws an exception:
but run- time exceptions if {nullpointerexception,arrayindexoutofboundsexception} is not required to be displayed by the program, it is automatically thrown by the Java virtual machine. It is not necessary to list it in the exception description. This exception is an error and will be automatically captured.
such as: int[] a=new int[4];System.out.println (a[4]);Although you do not have to catch exceptions, you can throw run-time exceptions in your code. If a run-time exception is thrown in the program, it can be handled and not handled. Processing:
Int[] A=new int[4];  try{  System.out.println (a[4]);//This statement throws an exception and does not execute subsequent try statement  System.out.print ("Hello");//Does not execute  }catch ( Exception e) {//find the corresponding Catch statement to execute   System.out.print ("Out of Bounds");  } System.out.print ("Hello");//Executes after exception is handled and does not execute if exception is not handled

If the handler jumps out of the try statement to execute the corresponding Catch statement, and the statement after the order is executed, then Hello will print out, if not processed, jump out of the program, do not print Hello, and print the E.printstacktrace () method as follows:Exception in thread "main" Java.lang.arrayindexoutofboundsexception:4At Jin.feng2.Exception01.main (exception01.java:18) 2, the finally keyword (in any case will be executed) whether it is return;break;continue;
for some code, you may want to be executed regardless of whether the exception in the try block is thrown. Generally applies to situations outside of memory and recycling. (Memory recycling is automatically reclaimed by the garbage collector)
when you want to restore resources out of memory to their initial state, you need to use the finally clause. such as: already open file or network connection, draw graphics on the screen, switch and so on.
Try  {   System.out.println ("point 1");   if (i==1) return;   System.out.println ("point 1");   if (i==2) return;  } catch (Exception e) {   e.printstacktrace ();  }  finally{   System.out.println ("00000");  } Main () f (1);  F (2);

Outputpoint 100000Point 1Point 100000A finally is executed before returning, that is, the finally is executed first and then the return is executed. the misuse of the Finally keyword causes an exception to be lost:The first is to call finally before the exception is processed and throw another exception in the finially. The previous exception will be lost!
{   try {   throw new RuntimeException ();} finally {  System.out.println ("E");  Return }

//outputJin.feng2.SimpleException2Another exception loss is an exception that is not processed, and a return is executed in finally 3 . Limitations of exceptions When overriding a method, only the exception listed in the exception description of the base class method can be thrown. You cannot overload a method based on an exception description, an exception that appears in the exception description of a base class method, and does not necessarily appear in a derived class
{   try {   throw new RuntimeException ();} finally {  System.out.println ("E");  Return }

in the exception description of the method, this is the opposite of the inherited rule. In inheritance, the method of the base class must appear in the derived class.

Exception restriction: For inheriting classes, if the overridden method has an exception description, the exception class listed must be a subset of the exception class listed by the method in the base class

Class MyException1 extends Exception {}class a {public    void proc () {    }    }class B extends A {    //Compile error: Because A.PR OC no exception description, so the subclass can not have an exception description    //solution is for A.proc Plus exception description: throws MyException1    //or in the throw new MyException1 (); Add a try block and remove the exception description public    void proc () throws MyException1 {        throw new MyException1 ();}    } Class MyException1 extends Exception {}class MyException2 extends Exception {}class A {public    void proc () throws MyEx Ception1 {    }    }class B extends A {    //error: Because A.proc only declared MyException1 exception public    void Proc () throws MyException2 {    }}


The constructor is an exception, and the inheriting class can declare more exception classes, but must add the exception class declared by the base class:

Class MyException1 extends Exception {}class MyException2 extends Exception {}class a {    a () throws MyException1 {     } public    void Proc () throws MyException1 {    }    }class B extends A {    B () throws MyException1, MyException2 { c6/>}}

when a class implementation inherits an abstract class and an interface, this abstract class and interface have a method is the same, but the exception description is not the same, at this time to take into account the abstract class and interface exception description, the implementation of this method must be the intersection of the two exception description.
Abstract Classpublic abstract void event () throws Baseballexception;//interfacepublic void event () throws rain;// Implement Classpublic void Event () {}

Must be intersection, so empty 4. Stack trajectoryThe information provided by the Printstacktrace () method can be accessed directly by means of the Getstacktrace () method, which returns an array of elements from the stack track, with element 0 representing the top of the stack, the last method called. Called First, and then pops up. void Printstacktrace ();//outputjava.lang.RuntimeExceptionAt Jin.feng2.Exception01.main (exception01.java:26)
public class exception03{static void F () {  try  {   throw new Exception ();  }  catch (Exception e)  {for   (stacktraceelement ste:e.getstacktrace ())   System.out.println ( Ste.getmethodname ());  } } static void G () {f ();} static void H () {g ();} public static void Main (String args[]) {f (); System.out.println ("____________"); g (); System.out.println ("____________"); h ();}}

OutputFMain____________FgMain____________FghMain re-throws the exception: the same exception is thrown in the catch. If you simply re-throw the current exception object, the Printstacktrace () method will show the stack of calls to the original exception throw point, rather than the information of the re-throw point. If you want to follow this new message, you can call the Fillinstacktrace () method. Thatthrow E.FillinstacktraceIf you re-throw another exception, the previous exception stack cannot be saved, but you want to save the information of the original exception-the exception chain you need to use the Initcause () method. such as E. Initcause (new nullpointerexception); throw e;

Java in-depth understanding of the anomalies

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.