Chapter XII stumbled exception (b)

First, abnormal and logging

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;

class LoggingException extends Exception{
    private static Logger logger = Logger.getLogger("LoggingException");
    public LoggingException() {
        StringWriter trace = new StringWriter();
        printStackTrace(new PrintWriter(trace));
        logger.severe(trace.toString());
    }
}
public class Demo6 {
    public static void main(String[] args) {
        try {
            throw new LoggingException();
        }catch(LoggingException e) {
            System.err.println("Caught " + e);
        }
    }
}
View Code

 

Output:

 

Second, the stack trace

public class Demo7 {

    void f1() throws Exception {
        throw new Exception();
    }
    void f2()throws Exception { f1(); }
    void f3()throws Exception { f2(); }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            Demo7 d = new Demo7();
            d.f3();
        }catch(Exception e) {
            for(StackTraceElement s : e.getStackTrace()) {
                System.out.println(s);
            }
        }
    }

}
View Code

 

Output:

 

Results Description: getStackTrace () This method returns an array of elements in the stack trace StackTraceElement configuration, each stack frame is the layer stack trace function is called. (With virtual machine stack stack frame).

Third, re-thrown

Example a: message content and unrelated to handling exceptions in the exception object that one method

public class Demo8 {

    void f() {
        try {
            throw new Exception("My Exception");
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    void g() { f(); }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Demo8 d = new Demo8();
        d.f();
    }

}
View Code

 

Output:

 

Results Description: exception object message content and exception handling location-independent, stack trace bottom of the stack is always main ();

 

Example Two: fillInStackTrace () rethrows with a new message

public  class Demo9 { 
    
    void F () throws Exception {
         the throw  new new Exception ( "from F ()" ); 
    } 
    // throw exception original 
    void G () throws Exception {
         the try { 
            F (); 
        } the catch (Exception E) { 
            System.out.println ( "G (), e.printStackTrace ():" ); 
            e.printStackTrace (the System.out); 
            the throw E; 
        } 
    } 
    // the original record the current call stack exception message, and cover original message 
    void H () throws Exception {
        try {
            f();
        }catch(Exception e) {
            System.out.println("f(), e.printStackTrace():");
            e.printStackTrace(System.out);
            //这里throw类似方法调用,fillInStackTrace()返回Throwable类
            throw (Exception)e.fillInStackTrace();
        } 
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Demo9 d = new Demo9();
        try {
            d.g();
        }catch(Exception e) {
            System.out.println("main() e.printStackTrace()");
            e.printStackTrace(System.out);
        }
        
        try {
            d.h();
        }catch(Exception e) {
            System.out.println("main() e.printStackTrace()"); 
            e.printStackTrace(System.out);
        }
    }

}
View Code

 

Output:

 

 

Results show that: fillInStackTrace () method will throw the current exception covered call stack information point method throws an original point of call stack information.

 

Fourth, abnormal chain

Abnormal chain: capture an exception after another throw an exception, and the preservation of the original exception information.

Use Case: General handling exceptions in the constructor, and then another will throw an exception, because the caller did not want to mistakenly think that the object was successfully established. But try not to write the constructor throws an exception, the coding would be more trouble, it should be safe as soon as possible so that the object is initialized and established.

 

 

Example one:

public class Demo10 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Demo10 d = new Demo10();
        try {
            d.test();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    void test() {
        try {
            int i = 10/0;
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

}
View Code

 

Output:

 

Results Description: like directly cause class constructor accepts only Error, Exception, RuntimeException. Other types require the use of the initCause () method of connection. In fact, most of the exception class methods are inherited from Throwable.

 

Example 2:

import java.io.IOException;

class MyException extends Exception{}

public class Demo11 {

    
    static void test() throws MyException{
        try {
            throw new IOException();
        }catch(Exception e) {
            MyException m = new MyException();
            m.initCause(e);
            throw m;
        }
    }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            test();
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

}
View Code

 

Output:

 

 

Results show: call initCause () routine, either immediately call in the creation of unusual or abnormal call in the constructor.

 

Example 3: "check exception is" packaged "is not checked exception"

 

public class Demo13 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            test();
        }catch(Exception e) {
            e.printStackTrace();
            try {
                throw (Exception)e.getCause();
            }catch(Exception e1) {
                System.out.println("getCause():");
                e1.printStackTrace();
            }
            
        }
    }
    
    static void test() {
        try {
            throw new Exception();
        }catch(Exception e) {
            throw new RuntimeException(e);
        }
    }

}
View Code

 

Output:

Results Description: getCause () method of Wang EENOW text, is used to obtain a Cause, and returns the class Throwable.

 

Fifth, abnormal loss

 Example:

public class Demo12 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            throw new RuntimeException();
        }finally {
            return;
        }
    }

}

 

Results show that: part of the code does not throw any exceptions, but a warning: finally module does not compile.

 

Sixth, unusual restrictions

1, when the coating method, only the base class method can throw exceptions in the exception described. (Abnormality may be described in a subclass of) this does not affect certain common code.

2, if implemented or inherited class, the method has the same name, making coverage to take subset throws statement.

3, when the upward transition carrying out, when referring call the base class method to capture the base class for exceptions in this method should simply do not know the actual type of the base class reference for the compiler, so not compile.

Example:

 

import java.io.IOException;

class A {
    void print() throws IOException {
            System.out.println("A");
            throw new IOException();
    }
}
public class Demo12 extends A{

    void print() {
        System.out.println("Demo12");
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        try {
            A a = new Demo12();
            a.print();
        }catch(Exception e) {
            e.printStackTrace();
        }
        
    }

}
View Code

 

 

Output:

Demo12

 

Guess you like

Origin www.cnblogs.com/mgblogs/p/11412333.html