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方法在声明时将异常抛出 方法本身不处理该异常即方法内不存在catch

//当调用该方法时 需要对异常进行处理

//如果不catch处理 可以像createNewFile方法一样通过 throws Exception 将异常抛给调用当前方法的上一级

// }

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 但打开文件需要关闭

reader.close();

//这里close()的异常也随着throws抛给了上一级 这里也可以对close进行完整的try catch

}

}

public static void upper(){

// readFile("C:/a.txt");

//在调用readFile方法时由于该方法throws Exception 所以这里需要处理抛出的异常

try {

//ctrl+alt+T快捷键调用try/catch包裹surround with

readFile("C:/a.txt");

} catch (Exception e) {

throw new RuntimeException(e);

//自动生成try/catch 抛出新的运行时异常对象

}

//如果当前方法不想处理异常 除了surround with try/catch idea还提示Add exception to method signature 向方法签名添加异常 即throws Exception

}

public static void main(String[] args) throws Exception{

//将main方法的异常抛出 会交由JVM虚拟机处理

}

}

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章