以下内容来自marschen的java4android视频教程
本集主要内容.
1.什么是异常.
2.异常的分类.
3.try ... catch ... finally结构的使用.
1.异常:中断了正常指令流的事件.
是程序在运行的过程当中产生的,跟编译没有半毛钱关系.
程序语法是正确的.运行也可能产生异常.
2.异常的分类
JDK所提供的异常类.
Throwable---|--> exception ----->-->| runtimeException
| |-->|
|-- >Erorr
3.try ... catch 实例.
finally,无论出不出异常,都会执行finally.
//uncheck exception 这类异常,可以通过编译. 在不加try ,,,catch的条件下可以通过编译.
class Test{
public static void main(String agrs[]){
System.out.println(1);
//uncheck exception
try{
System.out.println(2);
int i = 1 / 0 ;
System.out.println(3);
}
catch(Exception e){
e.printStackTrace();
System.out.println(4);
}
finally{
System.out.println("finally");
}
System.out.println(5);
}
}
//check Exception这类异常,如果不加try....catch.....就无法通过编译.
class TestCheck{
public static void main(String args[]){
//check exception
try{
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
System.out.println(4);
}
finally{
System.out.println("finally");
}
}
}
finally 就是不管异常出不出现都要执行, 这个在对于打开一个文件的时候,不管出不出错,我们都要去关闭它.
所以像文件关闭这样的操作就适合放在这个finally里面.
总结:
1.程序员对Error无能为力,只能处理Exception
2.对异常的处理关系到系统的健壮性
3.使用try ... catch ... finally来处理可能出现的异