1.常见的错误
编译错误:程序编写时,键入错误的关键字或标识符、遗漏标点符号、赋值时数据类型不匹配等错误。
运行错误:java程序执行时因非法操作或操作失败等原因产生的错误。例如:除数为0、数组越界、文件没找到等
逻辑错误:木有得到预期结果
2.异常处理
针对的是程序运行时非正常情况。java提供了一种专门的类进行负责--Exception。
Java中的Exception机制优点:进行分类,有层次性,接口良好;处理异常程序与原程序分离,降低耦合度;异常事件作为对象,父类与子类进行区分,使用和处理灵活
有5个关键字: try、catch、throw、throws、catch
Throws:Lists the exception a method could throw.
Throw: Transfers control of the method to the exception handler.
Try: Openning exception-handling statement.
Catch: Captures the exceptions.
Finally: Runs its code before terminating the program.
在Try中发现异常,Throw给catch进行处理,最后无论如何也要执行finally。
一般咱们写程序,都是在一些语句中(其实也是函数)抛出异常。Throws,其使用是在throw异常的方法定义的时候使用,即说明一个函数执行的时候会throw出那些exception,eg:public static int num(int i) throws ArithmetricException ,该方法会抛出一个异常。
对于异常的嵌套,总的理解就是:异常抛出后,如果有处理,它就会被处理掉后消失;如果没有处理,将会从产生的地方向调用的上一层继续保持throw,一直到有catch把它给处理掉。异常在嵌套的时候,不单单指的是在try阶段了,try阶段会抛出,catch阶段也可能,最后在finally阶段也可能,但是把握一个原则,即:如果抛出的异常在本层次内没有被处理掉,它就会向上窜,窜到被处理为止;同时,在本层内抛出的异常,虽然木有被处理掉,会被传到上层,但是在传之前或者说程序结束之前,本层的finally会被执行的。
示例:
public class TestException {
public TestException() {}
boolean testEx() throws Exception{
boolean ret = true;
try{
ret = testEx1();}
catch (Exception e){
System.out.println("testEx, catch exception");
ret = false;
throw e;}
finally{
System.out.println("testEx, finally; return value="+ret);
return ret;
}
boolean testEx1() throws Exception{
boolean ret = true;
try{
ret = testEx2();
if (!ret){
return false;}
System.out.println("testEx1, at the end of try");
return ret;
}
catch (Exception e){
System.out.println("testEx1, catch exception");
ret = false;
throw e;
}
finally{
System.out.println("testEx1, finally; return value="+ret);
return ret;
}
}
boolean testEx2() throws Exception{
boolean ret = true;
try{
int b=12;
int c;
for (int i=2;i>=-2;i--){
c=b/i;
System.out.println("i="+i);
}
return true;
}
catch (Exception e){
System.out.println("testEx2, catch exception");
ret = false;
throw e;
}
finally{
System.out.println("testEx2, finally; return value="+ret);
return ret;
}
}
public static void main(String[] args) {
TestException testException1 = new TestException();
try{
testException1.testEx();
}catch(Exception e){
e.printStackTrace();
}
}
}
----
----
----
答案:
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false