Java日誌第34天 2020.8.8
阿新 • • 發佈:2020-08-08
異常
異常的處理
throws
import java.io.FileNotFoundException; public class Demo01Throws { public static void main(String[] args) throws FileNotFoundException { readFile("C:\\b.txt"); } public static void readFile(String name) throws FileNotFoundException { if(name != "C:\\a.txt"){throw new FileNotFoundException(); } System.out.println("檔名正確!"); } }
try...catch
import java.io.FileNotFoundException; public class Demo01Throws { public static void main(String[] args) { try { //寫出可能會丟擲錯誤的程式碼 readFile("C:\\b.txt"); }catch (FileNotFoundException e) { System.out.println(e); } } public static void readFile(String name) throws FileNotFoundException { if(name != "C:\\a.txt"){ throw new FileNotFoundException(); } System.out.println("檔名正確!"); } }
Throwable類中三個異常處理方法
1. public String getMessage() 返回此throwable的簡短描述
import java.io.FileNotFoundException; public class Demo01Throws { public static void main(String[] args) { try { //寫出可能會丟擲錯誤的程式碼 readFile("C:\\b.txt"); } catch (FileNotFoundException e) { System.out.println(e.getMessage());//返回此throwable的簡短描述 } System.out.println("後續程式碼"); } public static void readFile(String name) throws FileNotFoundException { if(name != "C:\\a.txt"){ throw new FileNotFoundException("檔名錯誤!"); } System.out.println("檔名正確!"); } }
2. String toString() 返回此throwable的詳細訊息字串
import java.io.FileNotFoundException; public class Demo01Throws { public static void main(String[] args) { try { //寫出可能會丟擲錯誤的程式碼 readFile("C:\\b.txt"); } catch (FileNotFoundException e) { System.out.println(e.toString());//返回此throwable的詳細訊息字串 } System.out.println("後續程式碼"); } public static void readFile(String name) throws FileNotFoundException { if(name != "C:\\a.txt"){ throw new FileNotFoundException("檔名錯誤!"); } System.out.println("檔名正確!"); } }
結果如下:
3. void printStackTrace() JVM列印異常物件,預設此方法,列印的異常資訊是最全面的
import java.io.FileNotFoundException; public class Demo01Throws { public static void main(String[] args) { try { //寫出可能會丟擲錯誤的程式碼 readFile("C:\\b.txt"); } catch (FileNotFoundException e) { e.printStackTrace();//JVM列印異常物件,預設此方法,列印的異常資訊是最全面的 } System.out.println("後續程式碼"); } public static void readFile(String name) throws FileNotFoundException { if(name != "C:\\a.txt"){ throw new FileNotFoundException("檔名錯誤!"); } System.out.println("檔名正確!"); } }
結果如下:
finally程式碼塊
finally程式碼塊中的程式碼無論是否出現異常都會執行
注意事項:
1.finally不能單獨使用,必須與try一起使用
2.finally一般用於資源釋放(資源回收),無論程式是否出現異常,最後都要資源釋放(IO)
import java.io.FileNotFoundException; public class Demo01Throws { public static void main(String[] args) { try { //寫出可能會丟擲錯誤的程式碼 readFile("C:\\b.txt"); } catch (FileNotFoundException e) { e.printStackTrace();//JVM列印異常物件,預設此方法,列印的異常資訊是最全面的 } finally { System.out.println("資源釋放"); } System.out.println("後續程式碼"); } public static void readFile(String name) throws FileNotFoundException { if(name != "C:\\a.txt"){ throw new FileNotFoundException("檔名錯誤!"); } System.out.println("檔名正確!"); } }