最美情侣中文字幕电影,在线麻豆精品传媒,在线网站高清黄,久久黄色视频

歡迎光臨散文網(wǎng) 會員登陸 & 注冊

java異常拋出throws

2022-07-09 21:13 作者:虛云幻仙  | 我要投稿

/**
* 使用throws將異常拋出
*/

public class Test03 {
// ? ?public static void createFile(String path){
// ? ? ? ?File f = new File(path);
// ? ? ? ?f.createNewFile();
? ? ? ?//打開createNewFile()方法源碼:public boolean createNewFile() throws IOException
? ? ? ?//createNewFile方法在聲明時將異常拋出 方法本身不處理該異常即方法內(nèi)不存在catch
? ? ? ?//當(dāng)調(diào)用該方法時 需要對異常進行處理
? ? ? ?//如果不catch處理 可以像createNewFile方法一樣通過 throws Exception 將異常拋給調(diào)用當(dāng)前方法的上一級

// ? ?}

? ?public static void readFile(String path) throws Exception{
? ? ? ?FileReader reader = null;
? ? ? ?try{
? ? ? ? ? ?reader = new FileReader(path);
? ? ? ? ? ?System.out.println((char) reader.read());
? ? ? ?}finally{
? ? ? ? ? ?//throws異常無需catch 但打開文件需要關(guān)閉
? ? ? ? ? ?reader.close();
? ? ? ? ? ?//這里close()的異常也隨著throws拋給了上一級 這里也可以對close進行完整的try catch
? ? ? ?}

? ?}
? ?public static void upper(){
// ? ? ? ?readFile("C:/a.txt");
? ? ? ?//在調(diào)用readFile方法時由于該方法throws Exception 所以這里需要處理拋出的異常
? ? ? ?try {
? ? ? ? ? ?//ctrl+alt+T快捷鍵調(diào)用try/catch包裹surround with
? ? ? ? ? ?readFile("C:/a.txt");
? ? ? ?} catch (Exception e) {
? ? ? ? ? ?throw new RuntimeException(e);
? ? ? ? ? ?//自動生成try/catch 拋出新的運行時異常對象
? ? ? ?}
? ? ? ?//如果當(dāng)前方法不想處理異常 除了surround with try/catch ?idea還提示Add exception to method signature 向方法簽名添加異常 即throws Exception
? ?}

? ?public static void main(String[] args) throws Exception{
? ? ? ?//將main方法的異常拋出 會交由JVM虛擬機處理
? ?}
}

java異常拋出throws的評論 (共 條)

分享到微博請遵守國家法律
敦煌市| 都安| 卢氏县| 青河县| 通州区| 西青区| 南皮县| 科技| 玉门市| 永顺县| 桃源县| 中方县| 孝感市| 广德县| 贵德县| 会理县| 漯河市| 佛坪县| 黔西县| 淮阳县| 泰来县| 麦盖提县| 德江县| 兖州市| 宝山区| 台南县| 合山市| 柳河县| 普定县| 彭阳县| 平度市| 石嘴山市| 桓台县| 卢龙县| 乳源| 龙岩市| 广汉市| 大厂| 宜兴市| 安宁市| 巩留县|