Mic*_*rdt 15
for(File f : files){
try {
process(f); // may throw various exceptions
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
Run Code Online (Sandbox Code Playgroud)
Col*_*ert 11
你必须使用try/catch/finally集团.
try{
//Sensitive code
} catch(ExceptionType e){
//Handle exceptions of type ExceptionType or its subclasses
} finally {
//Code ALWAYS executed
}
Run Code Online (Sandbox Code Playgroud)
try 将允许您执行可能引发异常的敏感代码.catch 将处理特定异常(或此异常的任何子类型).finally 即使抛出异常而没有捕获异常,也会帮助执行语句.在你的情况下
for(File f : getFiles()){
//You might want to open a file and read it
InputStream fis;
//You might want to write into a file
OutputStream fos;
try{
handleFile(f);
fis = new FileInputStream(f);
fos = new FileOutputStream(f);
} catch(IOException e){
//Handle exceptions due to bad IO
} finally {
//In fact you should do a try/catch for each close operation.
//It was just too verbose to be put here.
try{
//If you handle streams, don't forget to close them.
fis.close();
fos.close();
}catch(IOException e){
//Handle the fact that close didn't work well.
}
}
}
Run Code Online (Sandbox Code Playgroud)
资源: