Java – 常见的例外状况

Java物件导向程式设计与SCJP认证明解

这一本书是这阵子在看的,作者很贴心的准备了SCJP总复习拟真试题给我们免费下载,真好!

我看到12-3-2 常见的例外状况,有关于编译器不会检核的RuntimeException的子孙类别有:

NullPointerException
IllegalArgumentException
NumberFormatException
ClassCastException
ArrayIndexOutOfBound:使用索引值存取阵列元素时,索引值超出阵列范围。
NegativeArraySizeException
ClassCastException
SecurityException
ArithmeticException

应检核例外:

java.text.ParseException
java.io.FileNotFoundException
java.io.IOException
java.sql.SQLException
java.lang.InterruptedException:使用索引值存取阵列元素时,索引值超出阵列范围。
java.lang.ClassNotFoundException

有没有看到ArrayIndexOutOfBound跟java.lang.InterruptedException这两个解释一模一样?怎会这样?对初学者来说不知道能不能分辨出来,还好ㄚ琪看了很多本SCJP了,所以一会儿就看到这个错误了,可能是作者那时在顾小孩的时候,贴错了吧!

java.lang.InterruptedException主要是执行绪非执行中而尝试中断所引发的例外处理,在执行绪那章会常常看到,原文手册是这样写:

‘Thrown when a thread is waiting, sleeping, or otherwise occupied, and the thread is interrupted, either before or during the activity. Occasionally a method may wish to test whether the current thread has been interrupted, and if so, to immediately throw this exception. The following code can be used to achieve this effect:

  if (Thread.interrupted())  // Clears interrupted status!
      throw new InterruptedException();

希望大家可以注意到,不会搞错!