学习问题记录(4) -- 异常
1. 简述Java Error类与Exception类的区别。
- 共同点:
- 都继承自第一层次的Object和第二层次的Throwable类
- 不同点:
- Error类:不是需要程序进行捕获和处理的,Error抛出后程序停止运行。
- Exception类:虚拟机系统根据异常的类型产生相应的异常对象,程序可以继续对抛出的异常进行捕获和相应的处理。
2. 简述异常处理的两种方式,并举例说明区别。
-
声明抛出处理:
- RunTimeException或其子类的异常,属于默认声明抛出。可以对其不做任何声名抛出或处理,交由调用该方法的地方处理(main方法交由JVM处理),编译时不会对可能产生异常地方给出提示;
- 其他异常类必须显示声明抛出。 例如
public static void main(String args[]) throws IOExceprion;
-
程序捕获处理:
通过使用try - catch - [finally]
语句块,用来对可能产生异常的代码产生的异常进行捕获,并根据其异常类型进行不同的操作。
3. 选取RuntimeException类的五个子类,编写抛出并捕获上述子类异常的程序。
import java.util.EmptyStackException; import java.util.Stack; class A{ int v = 6; public int getV() { return v; } } public class ExcpOp { public static void Arithmetic() { int a = 6, b = 0; try{ int c = a / b; } catch (ArithmeticException ae) { System.out.println(ae.getClass().getName()+" has been throw"); } finally { System.out.println("ArithmeticEp is over!\n"); } } public static void NullPointer() { try { A a = null; a.getV(); } catch (NullPointerException npe) { System.out.println(npe.getClass().getName()+" has been throw"); } finally { System.out.println("NullPointer is over!\n"); } } public static void EmptyStack() { Stack s = new Stack(); try{ s.push(5); s.pop(); System.out.println("Pop 1"); s.pop(); System.out.println("Pop 2"); } catch (EmptyStackException ese) { System.out.println(ese.getClass().getName()+" has been throw"); } finally { System.out.println("EmptyStack is over!\n"); } } public static void IndexOutOfBounds() { int[] a = new int[3]; for (int i = 0; i<3 ; i++ ) { a[i] = i; } try{ System.out.println(a[4]); } catch (IndexOutOfBoundsException ioe) { System.out.println(ioe.getClass().getName()+" has been throw"); } finally { System.out.println("EmptyStack is over!\n"); } } public static void NegativeArraySize() { try{ int[] a = new int[-3]; } catch (NegativeArraySizeException nase) { System.out.println(nase.getClass().getName()+" has been throw"); } finally { System.out.println("NegativeArraySize is over!\n"); } } public static void main(String[] args) { ExcpOp.Arithmetic(); ExcpOp.EmptyStack(); ExcpOp.IndexOutOfBounds(); ExcpOp.NegativeArraySize(); ExcpOp.NullPointer(); } }
4. 仿照例7.9,自己定义一个异常类,并在某场景下抛出该异常对象。
public class MyException extends Exception{ MyException(String msg) { super(msg); } public static void Throw(int a) throws MyException { if(a <= 666) { throw new MyException(" 输入不666 "); } } public static void main(String[] args) { int a = 660; try{ MyException.Throw(a); } catch (MyException me) { me.printStackTrace(); a = 668; } finally { System.out.println("此时 a = "+a); } } }