【问题标题】:Is there a way I could make a try-try-catch block?有没有办法可以制作一个 try-try-catch 块?
【发布时间】:2017-06-10 22:59:22
【问题描述】:

我正在使用 Apache POI 来尝试读取 word 文件,但即使您使用过 Apache POI,这仍然是可以回答的。在 HWPF.extractor 包中有两个对象,WordExtractor 和 Word6Extractor,这是旧版 Microsoft Word 格式的文本提取器。我正在尝试使用 try catch 语句来尝试 WordExtractor 对象。然后,如果引发错误,它应该在引发异常之前尝试 Word6Extractor。

我已经试过了:

try{
    WordExtractor example = new WordExtractor(...);
} try{
    Word6Extractor example = new Word6Extractor(...);
} catch(Exception e)
{
    //code to alert user to bad file type
}

如果您还有什么需要知道的,请告诉我,我会尽力提供。

【问题讨论】:

  • 放入catch块?
  • 您的代码不会按照您描述的方式运行,即使它是合法的,但事实并非如此,而且您可以在 30 秒内自行确定。不要只是发明不存在的语法。编写程序。
  • @EJP 我不是在发明不存在的语法我是在问一个关于如何正确执行我想做的事情的问题。没有必要写你相当粗鲁的评论,信不信由你我正在编写一个程序(一个几乎有 3000 行代码的程序)。我只是不习惯使用错误处理。

标签: java error-handling try-catch


【解决方案1】:

我认为您的代码唯一有问题的是语法!尽管对控制流使用异常非常麻烦,而且通常这是不好的编码习惯(或者我被教导过),但我相信这应该可以解决问题:

try{
  WordExtractor example = new WordExtractor(...);
} catch (Exception e){

  // If there is an exception thrown, we run the next block of code
  try 
  {
    Word6Extractor example = new Word6Extractor(...);
  } catch(Exception e)
  {
    //code to alert user to bad file type
  }

}

希望这能解决问题!

【讨论】:

  • 你知道我考虑过这样做,但在我的脑海中,它似乎不会做我想要的,但阅读代码让它看起来不同,我意识到这正是我需要的!谢谢!我也同意控制流这件事,但我认为这可能是在这种情况下最好的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
  • 1970-01-01
  • 2012-03-06
  • 2017-09-30
  • 2011-12-25
  • 1970-01-01
相关资源
最近更新 更多