java异常捕获(2) 获取异常的详细信息

  1. 如果需要访问异常对象的详细信息,可以在catch代码块中调用对应的方法来访问
  2. 以下几个方法为获取异常相关信息:
    1. getMessage()返回改异常信息的详细描述
    2. printStacktrace()将改异常的跟踪栈信息输出到标准错误输出
    3. printStackTrace(PrintStream S)将该异常信息输出到指定的输出流
    4. getStarckTrace()返回该异常的跟踪栈信息
  3. 代码示例
    
    package KnowIt;
    
    import java.io.FileInputStream;
    import java.io.IOError;
    import java.io.IOException;
    
    public class AccessException {
    
        public static void main(String args[]){
            try{
                FileInputStream fis = new FileInputStream("a.txt");
            }catch (IOException ioe){
                System.out.println(ioe.getMessage());
                ioe.printStackTrace();
            }
        }
    }
    //打印出信息为:
    //        a.txt (The system cannot find the file specified)

猜你喜欢

转载自blog.csdn.net/weixin_39452731/article/details/81748516