The Java object-oriented abnormal Detailed

Java's exception object-oriented [A]

The Java object-oriented abnormal [two]

Past Events: Previous We roughly summed up the unusual succession system, explained Exception and Error's top two categories are inherited from the parent class Throwable, but also talked about the difference between abnormal compile-time and run-time anomalies, abnormal talking about handling and treatment of several types of capture on the way.
Benpian nexus, abnormal summarized from the rest, but, after all, is now in the beginning stages, may not be able to experience abnormal use in the real scene at a convenience, so this just summed up what they learn on the current finishing, subsequent new experience It will be updated.

Capture the exception rule

  • No abnormality occurred during the execution of the try block, it is clear that there is no abnormality of course skipped catch clause .
  • Conversely, if an exception is thrown, it will skip the rest of the statements in the try , start looking for the exception handling code. The following exception handling code is to find the specific process:
  • From the current method, the method along the call chain, handling code to find an abnormality in the reverse direction of propagation of the exception.
  • From the first to the last check catch block, it is determined whether the match. If so, congratulations! Catch block directly into the processing exception statement is executed; and if not, the caller of the method abnormal passed, proceed in the same step callers: matching to process the upload ...... do not match
  • If you are not found until the last, the program will terminate, and print an error message in the print stage.
    If the method is relatively simple terms, in fact, it is very simple; if the method nested layers of it, the situation is Zeyang it, let's verify the above:
//主方法
public static void main(String[] args) {
    try{
    //调用m1()
        m1();
        System.out.println("ExceptionMyDemo.main");
    }catch (Exception e){
        System.out.println("ExceptionMyDemo.main.catch");
    }
}
//m1()
private static void m1(){
    try{
    //调用m2()
        m2();
        System.out.println("ExceptionMyDemo.m1");
    }catch (NullPointerException e){
        System.out.println("ExceptionMyDemo.m1.catch");
    }
}
//m2()
private static void m2(){
    String str = null;
    System.out.println(str.hashCode());
}
//测试结果:
ExceptionMyDemo.m1.catch
ExceptionMyDemo.main
  • You can see, m1 capture a null pointer exception thrown m2 type matching, direct treatment, it does not receive an exception, it will perform properly in the main method.
  • If we catch the exception type of m1 is replaced by other types, for example catch (ArithmeticException e), when the test results would look something like this:
//更改之后的测试结果:
ExceptionMyDemo.main.catch

Because m2 () throws an exception and not properly treated in m1, so throw up, find a treatment method in the main method, then perform the processing statement.

  • According to the above mentioned we deal if on the basis of the above after the change, then the main method of the exception clause deleted, then the result would be running Shane? Well, as expected, is the following results:

Because the exception thrown people did not deal with, it will print an exception stack trace on the console, anomalies thrown about, we are going to conduct a detailed analysis.

Access exception information

We mentioned that both the virtual machine throws an exception or do we take the initiative to throw, unusual error messages are included, so that we learn to better handle exceptions and then follow the above said, we have just seen is the exception stack trace:

  • public void printStackTrace(): The default trace information Throwable objects and the call stack to the standard error stream.
  • public String getMessage(): Returns a string description of the exception object information.
  • public String toString(): Exception information message is empty returns the full name of the exception class, otherwise returns 全名:messageform.
  • public StackTraceElement[] getStackTrace(): Returns the stack trace elements in the array, and represent the exception object associated stack trace information.

Abnormality on overridden method

  • No effect on abnormal method overloading.
  • When rewriting method, exceptions can not exceed the scope of the method the parent compiled method throws exception subclass thrown rewritten compile time .

finally Detailed

Famous aphorism: regardless of whether an exception occurs, finally modified clause will always be executed .

So we conducted a simple try:

public static void m2(){
    try{
        System.out.println("0");
        System.out.println(1/0);
        System.out.println("1");
    }
    catch (Exception e){
        System.out.println("2");
    }
    finally {
        System.out.println("3");
    }
    System.out.println("4");
}
//测试结果
0 2 3 4 被打印在控制台上
  • 1 is not printed can be seen, because the execution System.out.println(1/0);of the abnormality occurs, then into the catch block, the finally clause will be executed, and then the next statement after the try statement.
  • Imagine the following: If the received unusual instance type to another type does not match, then, that can not be captured properly, the outcome will happen? The results are as follows:

  • Obviously, this time finally results came out, even if you are out of the anomaly, I finally statement in the block must be executed in real-life scenarios for this release of resources played a key role, but the specific, because also no learning content behind it aside, some things are better after the experience will be more realistic number.
  • Note that there is a 4 point has not been printed, because there is no Exception caught, an exception will be thrown to the caller, so it will not execute System.out.println("4");.

However, a pseudonym for the tens of millions of why I started wondering, until we can return the method returns, Force Quit. So if you use the return statement in the try, finally beginning of the heart will not forget to continue to enforce it?

In front of high energy! Note that all units! ! !
Guess what, the results of these four methods is Shane?

private  static int m1(){
    try{
        return 1;
    }catch(Exception e){
    }
    return 2;
}
private static int m2(){
    try{
        return 1;
    }finally {
        return 2;
    }
    //使用finally子句时可以省略catch块
}
private static int m3(){
    try{
        return 1;
    }finally {
        try{
            return 2;
        }finally {
            return 3;
        }
    }
}
private static int m4(){
    int i = 4;
    try{
        return i++;
    }finally {
        i++;
    }
}

The answer is revealed: are: 1,2,3,4. You guessed it right? Haha ......

I think the answer should be no doubt that the first three, but this is the fourth bit outrageous. Not to say that finally statement will execute it, which went to perform it, and if you perform, you should not turn into 6 i do it?
Amount ...... Keke, Well, I'm a bit confused, but after some advice, some know a little:

  • Before performing try, if there is finally back, we will try to return in the delay process, that results into the area i = 4.
  • Then in the calculation of area increment operator becomes 5, finally statement will be executed, but only in the calculation of the area since increased to 6, and the result was that the area of ​​the original 4.
  • Do not believe it, you can look at the value of i i ++ finally statement behind it! It is 6! So finally clause must perform it is beyond doubt is!

But if the change is a reference data type variable, it will change accordingly, and people in the village of address, change is itself. I'll be a little simple example here in Austria:

public static Student m(){
    Student s = new Student();
    try{
        s.age = 20;
        s.name = "天乔";
        return s;
    }finally {

        s.name = "巴夏";
        s.age = 2;
    }
}
//测试结果
//Student{age=2, name='巴夏'}

This article describes if inappropriate, but also hope the comments section criticism Oh!

Guess you like

Origin www.cnblogs.com/summerday152/p/12180854.html