1.定義
異常指的是在程序運行過程中發生的異常事件
2.java異常分類
(1).檢查異常:java強制要求要解決或者拋出異常
(2).非檢查異常(運行時異常):不必強制去處理可能發生的異常
public static void test(int i) throws UnsupportedEncodingException {
int j = 5/i; //這裏的i有可能等於0,但是只有在運行的時候纔會知道
System.out.println(j);
String filePath = "C:\\Users\\MES\\Desktop\\gggg.txt";
File file =new File(filePath);
//檢查異常 java會強制你處理或者拋出異常
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw e;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
3.Throwable
Throwable 是 錯誤(Error)和 異常(Exception)的父類
java通常不捕獲錯誤;只對Exception
Exception有兩個主要的子類IOException和RuntimeException
RuntimeException裏面的子類是unchecked異常,既未經檢查的異常,Exception下的除此之外的子類都是檢查異常
4.異常捕獲(try/catch)
java中使用try/catch捕獲異常,可以嵌套使用
5.Finally
無論是否發生異常都不會影響Finally裏面的程序的執行
一般用來關閉或者釋放資源
6.異常拋出和聲明(throws/throw)
(1)異常拋出(throw):確定會引發異常
(2)異常聲明(throws):在定義方法上,代表可能會出現異常
7.自定義異常
1.先寫一個方法,然後繼承Throw或者Exception等方法
package throwable;
public class MyThrow extends Exception {
public MyThrow(){
super();
System.out.println("我自己的異常!!!");
}
}
然後在代碼中拋出自己的定義的異常類
public static void test(int i) throws UnsupportedEncodingException, MyThrow {
String filePath = "C:\\Users\\MES\\Desktop\\gggg.txt";
File file =new File(filePath);
try {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath),"UTF-8");
throw new MyThrow(); //這裏拋出自己定義的異常
} catch (UnsupportedEncodingException e) {
throw e;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
最後在使用這個方法時,處理這個異常類
public static void main(String arg[]) throws UnsupportedEncodingException {
try {
test(0);
} catch (MyThrow myThrow) {
myThrow.printStackTrace();
}
}
最終結果:
throwable.MyThrow
我自己的異常!!!
at throwable.Dome01.test(Dome01.java:21)
at throwable.Dome01.main(Dome01.java:9)