1、异常分为两种,一种是检测时异常(出去RuntimeException 之外,所有的Exception以及其子类),一种是运行是异常。
2、运行时异常一般发生在调用处,或者是在引起内部结构发生变化的时候引起。
3、为了能够处理异常,所以要在函数声明处生命异常。
4、RuntimeException是在程序正常运行期间发生的,可以不去处理。Error是JVM错误。
5、throw和throws 实际上没有什么区别,只是看起来长得像罢了,throw是写在函数内部,throws写在函数声明处,并且可以抛出多个,各个异常之间用分号隔开。
6、抛出和生声明 、try{}catch(){}finally{} 各自和各自组合
7、try在检测时候,如果发生异常,会把异常对象抛给catch进行处理。
8、异常对象有自己独特的字符串表现形式,其他的对象HashCode()居多。
9、getMessage()、printStackTrace()。
package 异常处理;
class FuShuIndexException extends Exception {
public FuShuIndexException() {
super();
}
FuShuIndexException(String string) {
super(string);
}
}
class Demo2 {
public void show(int []arr,int index){
try{
if(index<0){
throw new FuShuIndexException("负数角标异常!");
}
}catch(FuShuIndexException e){
System.out.println(e.getMessage());
e.printStackTrace();
System.out.println(""+e);
}finally{
System.out.println("over");
}
}
}
public class Test08 {
public static void main(String[] args) {
int []arr=new int[2];
Demo2 d=new Demo2();
d.show(arr,-1);
System.out.println("还是会执行的!");
}
}
---------------------------------------------------------------------------------------------------
package 异常处理;
class Demo3 {
public void show(int[] arr, int index) throws FuShuIndexException {
if (index < 0) {
throw new FuShuIndexException("负数角标异常!");
}
}
}
public class Test09 {
public static void main(String[] args) {
int []arr2=new int[2];
Demo3 demo3=new Demo3();
try {
demo3.show(arr2, -1);
} catch (FuShuIndexException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("还是会允许的,因为异常被处理掉了!");
}
}