简述Java Error与Exception的区别。
Error是所有错误类的祖先类,Exception是所有异常类的祖先类。前者不是程序需要捕获与进行处理的,当Error发生时,程序会立即停止
简述异常处理的两种方式
这两种方式分别为声明抛出处理与程序捕获处理。而声明抛出处理又分为隐式声明抛出与显式声明抛出;程序捕获处理则分为非嵌套与嵌套。
隐式声明抛出:程序方法对这类异常不作任何声明抛出或者处理,直接交给调用该方法的地方处理,且程序并不会编译失败也不会对产生异常的代码给出提示。
显式声明抛出:显式地通过throws向上级抛出异常。例如public static void main(String args[]) throws IOExceprion;
程序捕获处理:
通过使用try - catch - [finally]语句块,用来对可能产生异常的代码产生的异常进行捕获,并根据其异常类型进行不同的操作。
选取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();
}
}
仿照例7.9,自己定义一个异常类,并在某场景下抛出该异常对象。
public class MyException extends Exception{
MyException(String msg) {
super(msg);
}
public static void Throw(int a) throws MyException {
if(a !=123456) {
throw new MyException(" 错误 ");
}
}
public static void main(String[] args) {
int a = 660;
try{
MyException.Throw(a);
} catch (MyException me) {
me.printStackTrace();
a = 123456;
} finally {
System.out.println("此时 正确");
}
}
}