java提供了兩種處理方法處理異常:
java的異常處理:抓拋模型
1.抓:異常的處理分爲兩種(1、try-catch-finally 2、throws+異常的類型)
2.拋:手動的拋出(throw+異常類的對象)
throw new RuntimeException(“傳入的類型有誤”)
常見的異常:
1.數組下標越界的異常:ArrayIndexOutOfBoundsException
2.算術異常:ArithmeticException
3.類型轉換異常:ClassCastException
4.空指針異常:NullPointerException
5.文件不存在異常:FileNotFoundException
6.沒有可序列化的異常:NotSerializableException
使用try-catch-finally處理異常
try{
//可能出現異常的代碼
}catch{
//處理方式一
}catch{
//處理方式二
}finally{
//一定會執行的代碼
}
**注:**
1.try內聲明的變量,類似於局部變量,出了try{}語句,就不能被調用
2.finally是可選的。
3.catch語句內部是對異常對象的處理
使用throws拋出異常
public class test2 {
public static void main(String[] args) {
try {
method2();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void method2() throws Exception {
method1();
}
public static void method1() throws FileNotFoundException,IOException{
FileInputStream fis=new FileInputStream(new File("hello.txt"));
int b;
while((b=fis.read())!=-1){
System.out.println((char)b);
}
fis.close();
}
}