《2018年1月31日》【连续112天】
标题:异常(Excepction);
内容:
要点:程序遇到发生异常的语句后,会停止运行,但如果将异常catch,就可以继续运行了;
Java的异常处理机制:
try{
}catch(){
}catch(){
}....
实例:
int i=in.nextInt();
int[] a =new int[10];
try{a[i]=10;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界");
}
ArrayIndexOutOfBoundsException是数组越界的意思,诸如此类的异常叫系统运行时刻异常;
将上面的代码进行部分修改:
try{a[i]=10;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界");
System.out.println(e.getMessage());
System.out.println(e);
e.getStackTrace();
}
Console内容:
10
数组越界
10
java.lang.ArrayIndexOutOfBoundsException: 10
换种情况:
public static void h() {
g();
}
public static void g() {
f();
}
public static void f() {
int[] a =new int[10];
a[10]=10;
}
try{ h();
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界");
System.out.println(e.getMessage());
System.out.println(e);
e.printStackTrace();
}
System.out.println("main end");
10
java.lang.ArrayIndexOutOfBoundsException: 10
java.lang.ArrayIndexOutOfBoundsException: 10
at TES.test.f(test.java:13)
at TES.test.g(test.java:9)
at TES.test.h(test.java:6)
at TES.test.main(test.java:17)
main end
main end应该在at...之前的,不过跑起来是这样;
13是数组越界的行数,9是g()调用f()的行数,..最后mian在第17行调用h(),这叫调用堆栈;
函数异常:
1.函数里可以处理异常:
例:上例:
public static void g() {
try { f();
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("g exception");
}
Console:
g exception
main end
如果g()中是try{}catch(){...
throw e;
}
main中的try也会执行;
throw的对象只能说Throwable或其子类(常见的exception);
子类的异常可以被父类的catch(super){}捕捉到;
2.函数可以声明其可能的异常:
public static void h() throws Exception{
g();
}
声明后,使用该函数时必须加入try{h()}...
并且要catch它声明的异常;
ArrayIndexOutOfBoundsException
系统运行时刻异常是不用声明的 ;
3.继承的函数:
子类函数覆盖父类时,其声明的异常不能超过父类的该函数;
子类的构造函数必须包括父类构造函数的全部异常;
明日计划:学习;