java異常拋出throws
/**
* 使用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虛擬機處理
? ?}
}