1、 简述Java Error类与Exception类的区别。
Exception是所有异常类的祖先类; Error类是所有错误类的祖先类。它不是程序需要捕获和进行处理的,例如OutOfMemoryError(当Java虚拟机在为对象分配内存空间时,剩余的空间不够,同时也没有可以释放的内容时,将会发生这样的错误),不由程序进行捕获或处理,当Error发生时,程序将会停止。
2、 简述异常处理的两种方式,并举例说明区别。
- 声明抛出处理。包括隐式声明处理和显式声明处理。其中隐式声明抛出处理的特点是异常类型是RuntimeException或是其子类,程序方法可以对异常不作任何声明抛出或处理,直接交给调用该方法的地方处理,程序能编译通过,不会对可能产生异常的代码行给出提示;显式声明处理是通过
throws
显式抛出异常。
举例如下:
//隐式声明处理
public class TestArray {
private static int[] x;
public static void main(String[] args) {
System.out.println(x[0]);
}
}//NullPointerException
//显式声明处理
public class TestArray {
private static int[] x;
public static void main(String[] args) throws RuntimeException{
System.out.println(x[0]);
}
}
- 程序捕获处理。通过
try...catch...finally
语句对异常进行识别和捕获处理。包括非嵌套捕获和嵌套捕获。
举例如下:
//非嵌套捕获
import java.io.*;
public class Test{
public static void main(String[] args){
BufferedReader keyin = new BufferedReader(new InputStreamReader(System.in));
String c1;
int i=0;
String[] e = new String[2];
while(i<2){
try{
c1 = keyin.readLine();
e[i] = c1;
i++;
}
catch (IOException e1) {
System.out.println("系统有IO错误");
}
}
}
}
//嵌套捕获
public class Test {
public static void main(String[] args) {
int a,b,c;
a=67;
b=0;
try{
try{
c=a/b;
}
catch(ArithmeticException ae){
b = 10;
c = a/b;
System.out.println(a+"/"+b+"="+c);
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
3、选取RuntimeException类的五个子类,编写抛出并捕获上述子类异常的程序。(例如算术异常,空指针异常,类转换异常,数组越界异常等)
- 算术异常(ArithmeticException)
public class TestArithmetic {
public static void main (String[] args) {
int a,b,c;
a = 67;
b = 0;
c = a/b;
System.out.println(a + "/"+b+"="+c);
}
}
- 空指针异常(NullPointerException)
public class TestNullPointer {
private static int[] x;
public static void main(String[] args) {
System.out.println(x[0]);
}
}
- 类转换异常(ClassCastException)
public class TestClassCast {
public static void main(String[] args){
Object ob = new Integer(0);
System.out.println((String)ob);
}
}
- 数组下标越界异常(ArrayIndexOutOfBoundsException)
public class TestArrayIndexOutOfBounds {
public static void main(String[] args) {
String foo = args[1];
System.out.println("foo = " + foo);
}
}
- 空栈异常(EmptyStackException)
import java.util. *;
class TestEmptyStack {
public static void main(String[] args) {
Stack st = new Stack();
Object ob = st.pop();
}
}
4、仿照例7.9,自定义一个异常类,并在某场景下抛出该异常对象。
class MyException extends Exception {
MyException(String msg){
super(msg);
}
static void throwTwo(int x) throws MyException{
if(x % 2 != 0){
throw new MyException("x是奇数!");
}
else {
System.out.println(x);
}
}
public static void main(String[] args){
try{
int x = 3;
throwTwo(x);
}
catch(MyException e){
e.printStackTrace();
}
}
}