`
dasheng
  • 浏览: 146288 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

<java编程思想>学习笔记12 第12章 通过异常 处理错误

阅读更多

1,java的基本理念是:结构不佳的代码不能运行。

 

2,当异常抛出后,有几件事会随之发生。首先,同java的其他对象的创建一样,将使用new在堆上创建异常对象。然后,

 

当前的执行路径(它不能继续下去了)被终止,并且从当前的环境中弹出对异常的引用。此时,异常处理机制接管程序。并

 

开始寻找一个恰当的地方来继续执行程序。这个恰当的地方就是异常处理程序,它的任务就是将程序从错误状态中恢复,以

 

使程序要么换一种方式运行,要么继续运行下去。

 

3,异常的参数

 

所有标准的异常类都有两个构造器:

1个是默认构造器;另一个是接受字符串作为参数,以便把相关的信息放入异常对象的构造器。

 

4,能够抛出任意类型的Throwable对象,它是异常类型的根类。通常,异常对象中仅有的信息就是异常类型,除此之外不包含任何有意义的内容。

 

5,异常说明

 

java鼓励人们把方法可能会抛出的异常告知使用此方法的客户端程序员。

 

异常说明使用了附加的关键字throws,后面接一个所有潜在的异常类型的列表,看起来方法象这样:

 

void f() throws toolBig,TooSmall,DivZero {//

 

5,exception基类Throwable,方法如下:

 

String getMessage();

String getLocallizedMessage();

 

 

void printStackTrack();

 

void printStackTrack(PrintStream);

 

void printStackTrack(java.io.PrintWriter);

 

6,无论异常是否抛出,finally子句总会被执行。

 

class ThreeException extends Exception {}

public class FinallyWorks {
  static int count = 0;
  public static void main(String[] args) {
    while(true) {
      try {
        // Post-increment is zero first time:
        if(count++ == 0)
          throw new ThreeException();
        System.out.println("No exception");
      } catch(ThreeException e) {
        System.out.println("ThreeException");
      } finally {
        System.out.println("In finally clause");
        if(count == 2) break; // out of "while"
      }
    }
  }
} /* Output:

 

 

 

7,异常的丢失

 

class VeryImportantException extends Exception {
  public String toString() {
    return "A very important exception!";
  }
}

class HoHumException extends Exception {
  public String toString() {
    return "A trivial exception";
  }
}

public class LostMessage {
  void f() throws VeryImportantException {
    throw new VeryImportantException();
  }
  void dispose() throws HoHumException {
    throw new HoHumException();
  }
  public static void main(String[] args) {
    try {
      LostMessage lm = new LostMessage();
      try {
        lm.f();
      } finally {
        lm.dispose();
      }
    } catch(Exception e) {
      System.out.println(e);
    }
  }
} /* Output:

 

8,在finally子句中执行return造成异常的丢失

 

public class ExceptionSilencer {
  public static void main(String[] args) {
    try {
      throw new RuntimeException();
    } finally {
      // Using 'return' inside the finally block
      // will silence any thrown exception.
      return;
    }
  }
} ///:~

 

输出结果,发生了异常也没有任何输出。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics