课后习题:
exercise1:
package Exception;
public class Exercise1 {
public static void main(String[] args) {
try {
throw new Exception("abc");
} catch (Exception e) {
e.printStackTrace();
}
finally {
System.out.println("执行了");
}
}
}
exercise2:
public class Exercise2 {
void f() {
}
public static void main(String[] args) {
Exercise2 e2 = null;
try {
e2.f();
} catch (Exception e) {
e.printStackTrace();
}
}
}
exercise3:
package Exception;
public class Exercise3 {
public static void main(String[] args) {
try {
throw new ArrayIndexOutOfBoundsException();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
exercise4:
package Exception;
public class MyException extends Exception{
String s;
public MyException(String s) {
this.s =s;
}
void print() {
System.out.println(s);
}
public static void main(String[] args) {
try {
throw new MyException("abc");
} catch (MyException e) {
e.print();
e.printStackTrace();
}
}
}
exercise5:
来自原书文档。
public class Ex5 {
private static int[] ia = new int[2];
static int x = 5;
public static void main(String[] args) {
while(true) {
try {
ia[x] = 1;
System.out.println(ia[x]);
break;
} catch(ArrayIndexOutOfBoundsException e) {
System.err.println(
"Caught ArrayIndexOutOfBoundsException");
e.printStackTrace();
x--;
} finally {
System.out.println("Are we done yet?");
}
}
System.out.println("Now, we're done.");
}
}