异常分为:
1.运行时异常: 在程序运行过程中才会抛出的异常
2.检查型异常:编码过程中必须处理的异常
1定义:程序运行过程中出现的特殊情况(例如hashtable、treemap中不能存放null值,存入null就会报异常)
接触到的运行时异常:
String s="123a";
int i=Integer.parseInt(s);//java.lang.NumberFormatException 数字转化异常
Object obj1="123";
Day719_01 e=(Day719_01)obj1;//java.lang.ClassCastException //类异常
TreeSet set=new TreeSet();// java.lang.StringIndexOutOfBoundsExceptionset.add(12.2);
String str="123";
str.substring(4);//java.lang.StringIndexOutOfBoundsException 字符串下标越界异常
int [] arr= {};//java.lang.ArrayIndexOutOfBoundsException数组下标越界异常
arr[0]=12;
List list=new ArrayList();
list.get(1);//java.lang.IndexOutOfBoundsException 下标越界异常
Object obj=null;
obj.toString();//java.lang.NullPointerException 空指针异常
double b=12/0;//java.lang.ArithmeticException 计算异常
2.检查型异常
2.异常处理:File file =new File("D:Hello.java")//Java加载文件
FileInputStream fis=new FileInputStream(file);//FileNotFoundException 文件找不到异常
1.第一种处理异常的方式:try {} catch[] finally{}
//catch 如果抛出了指定的异常,执行的方案
finally不管是否抛出了一场都会执行的代码
//Java程序访问外部资源一般都会抛出检查类异常
File file;//try catch 是两个代码块 在catch中访问不到try中定义的局部变量
FileInputStream fis
try{
file =new File("D:Hello.java")//Java加载文件
fis=new FileInputStream(file);
//FileNotFoundException 文件找不到异常
}catch(FileNotFoundException e ){
//try 块抛出异常后,处理的预备方案
file=null;
fis=null;
e.printStackTrace();//打印异常信息 只是在开发测试过中调试用
}finally{
//不管运行成功 或者抛出异常与否 都会执行finally
if(fis==null){
fis.close();
}
}
第二种处理异常的方法:抛出异常
一个方法中可能会抛出异常,使用throws声明抛出的异常类型,throw表示抛出异常
注: 运行时异常在抛出时,必须使用throws进行声明
当一个类中需要抛出两种异常,用,隔开
//所有的RuntimeException的子类都是运行时异常
//Exception除了RuntimeException都是检查性异常
-------------------------------
throwable是Exception的父类 , Exception下还有一个很重要的error
声明一个自定义异常:
需要两个构造函数 一个是无参构造,另一个是存入异常信息的参数构造。
范围大的异常的catch放在后面
//重写的方法只能抛出范围更小的异常(检查性异常)
//不能抛出更多个异常
注:这里补充一个以前的return问题
这里执行了两次return



