Javaexception处理

即使在处理一组文件中的某些文件时发生exception,如何使用exception和exception处理来使我的程序继续运行?

我希望我的程序能够正常处理正确的文件,而对于那些导致程序exception的文件,它应该忽略。

问候,

magggi

for(File f : files){ try { process(f); // may throw various exceptions } catch (Exception e) { logger.error(e.getMessage(), e); } } 

你必须使用try / catch / finally集团。

 try{ //Sensitive code } catch(ExceptionType e){ //Handle exceptions of type ExceptionType or its subclasses } finally { //Code ALWAYS executed } 
  • try将允许您执行可能引发exception的敏感代码。
  • catch将处理特定exception(或此exception的任何子类型)。
  • finally将帮助执行语句,即使抛出exception并且没有捕获。

在你的情况下

 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. } } } 

资源:

  • oracle.com – 课程:例外
  • JLS – 例外

我猜你的编程新手是一个相当有趣的概念,因为问题可能发生在你的控制之外,你需要处理它。

基本前提是try catch块。

 try { //Your code here that causes problems } catch(exception ex) { //Your code to handle the exception } 

你’尝试’你的代码,如果引发exception,你就会“抓住”它。 并做你需要的。 catch块中还有一个补充,你可以在它下面添加{}。 基本上即使没有引发exception,最终代码仍然会运行。 您可能想知道这一点,但它经常用于流/文件处理等来关闭流。

在Sun(现在的Oracle)编写的教程中阅读有关javaexception的更多信息 – http://download.oracle.com/javase/tutorial/essential/exceptions/

 try { //Your code here that causes problems } catch(exception ex) { //Your code to handle the exception } finally { //Always do this, ie try to read a file, catch any errors, always close the file } 

您可能会问的问题是如何捕获不同的exception,即它是否为空引用,是否为零,是否找不到文件或文件不可写等。为此您在try下编写了几个不同的catch块,基本上对于每种类型的exception都有一个catch,使用“exception”基本上是一个catch all语句,就像if语句的堆栈一样,如果“exception”是第一个catch块,它将捕获所有内容,所以如果你有几个catch块确保exception是最后一个。

同样,这是一个有用但很大的主题,所以你需要阅读它。

由于您正在执行多个文件,因此您需要基本上执行循环,并且在循环内包含try / catch块。

所以即使一个文件失败,你抓住它,但继续运行,然后代码将无阻碍地循环到下一个文件。

只是抓住它可能抛出的繁琐而不做任何事情; 像人们说的那样吃它:)但至少记录它!

非常简洁的例子:

 try { your code... } catch (Exception e) { log here } 

通常情况下,我会这样做。

 ArrayList allEntries = getAllEntries(); for(Entry eachEntry:allEntries){ try{ //do all your processing for eachEntry } catch(Exception e{ ignoredEntries.add(eachEntry); //if concerned, you can store even the specific problem. } finally{ //In case of resource release } } if(ignoredEntries.size() > 0){ //Handle this scenario, may be display the error to the user } 

FileSystemException可能是您正在寻找的特定exception。

虽然,对于初学者来说更好的想法是捕获exception并使用它进行打印

System.out.println(e);

其中e是被捕获的例外。