
异常:运行期出现的错误
缓冲期溢出的漏洞-C数组下标越界
Java-java.lang-Exceptions-ArrayIndexOutOfBoundsException
捕获
try{ //有可能产生异常的语句
System.out.println(1/0);
} catch (ArithmeticException ae){ //遇到这异常该怎么办 ,自己定义逮到的异常对象的名字ae
System.out.println(“系统正在维护中”);
ae.printStackTrace(); //出错误的堆栈信息,全给你打印出来
}
系统正在维护中
java.lang.ArithmeticException: / by zero
at TestEx.main(TestEx.java:4)
java.lang - Exceptions - class Throwable(可被抛出的)
子类 - Error(系统的错误/虚拟机出错了/咱处理不了的错误)
- Exception(咱可处理的错误)
- RuntimeException(运行时出的错,产生的很频繁,一直处理太累,可catch,可不catch)
- 其他 (比如写了throws IOException,它是java.lang.Exception的子类,必须catch)
finally 后的语句一定会执行,进行资源的清除工作
main() throws Exception{} // 任何方法都能throws Exception,但main抛也太不负责了..交给运行时系统,堆栈把错误信息打印出来
public class TestEx {
public static void main(String[] args) {
try{
new TestEx().f2();
} catch(IOException e){
e.printStackTrace();
}
FileInputStream in = null;
try{
in = new FileInputStream("myfile.txt");
int b;
b = in.read();
while(b!=-1){
System.out.println((char)b);
b = in.read();
}
} catch (FileNotFoundException e) { //先小
e.printStackTrace();
} catch (IOException e){ //后大
System.out.println(e.getMessage());
} finally {
try{
in.close();
} catch(IOException e){
e.printStackTrace();
}
}
}
void m(int i) throws ArithmeticException{ //throws
if(i==0)
throw new ArithmeticException("divided by 0"); //throw
}
void f() throws FileNotFoundException,IOException{ //处理不了异常,往外抛就行
FileInputStream in = new FileInputStream("myfile.txt");
int b;
b = in.read();
while(b!=-1){
System.out.println((char)b);
b = in.read();
}
void f2() throws IOException{
/*
try{
f();
} catch(FileNotFoundException e){
System.out.println(e.getMessage());
} catch(IOException e){
e.printStackTrace();
}
*/
f();
}
}
自定义异常
重写方法需要抛出与原方法所抛出异常类型一致异常/不抛出异常




近期评论