异常(Exception)的学习
1.Throwsable 的兩個(gè)子類 Exception 和 Error
2.Exception 這是編譯期異常,可以捕獲處理
3.RuntimeException 表示運(yùn)行期間的異常,它是 Exception 的子類
4.Error 這是程序錯(cuò)誤,不可捕獲處理。例如,內(nèi)存溢出
5.throws 關(guān)鍵字,用于聲明可能拋出編譯異常,讓調(diào)用者處理異常。拋出的如果是運(yùn)行時(shí)異常,則可以不聲明。方法內(nèi)使用 throw 關(guān)鍵字拋出編譯時(shí)異常,就必須使用關(guān)鍵字 throws 在方法簽名處聲明可能拋出的異常
6.如果異常拋給 JVM 處理,JVM 會(huì)打印異常信息,然后直接停止程序
7.使用 try…catch 捕獲異常,后面的程序照常執(zhí)行
運(yùn)行期異常:
NullPointerException
ArrayIndexOutOfBoundsException,繼承自 IndexOutOfBoundsException
編譯期異常:
FileNotFoundException,它繼承自 IOException
IOException,它繼承自 Exception
自定義異常類:
繼承自 Exception,是編譯時(shí)異常
繼承自 RuntimeException,是運(yùn)行時(shí)異常,無(wú)需處理
代碼示例:
public class Demo01Exception {public static void main(String[] args) {try {readFile("/users/home/test.txt");System.out.println(8888); // 捕獲到異常,此行代碼不會(huì)執(zhí)行} catch (IOException e) {e.printStackTrace();} finally {System.out.println(5555); // 有沒(méi)有異常,此行代碼都會(huì)執(zhí)行}System.out.println(9999); // 有沒(méi)有異常,此行代碼都會(huì)執(zhí)行}static void readFile(String path) throws IOException {if (!path.endsWith(".txt")) {throw new IOException("文件格式不對(duì)");}System.out.println(7777); // 拋出異常,此行代碼不會(huì)執(zhí)行} }總結(jié)
以上是生活随笔為你收集整理的异常(Exception)的学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 预防近视的方法
- 下一篇: 怎么看电脑硬盘的寿命如何查看电脑硬盘信息