【问题标题】:Catching thrown exceptions with an Exception class I created使用我创建的 Exception 类捕获抛出的异常
【发布时间】:2015-10-01 04:54:16
【问题描述】:

GraphicsFileNotFoundException.java 中,我只有一个FileNotFoundException 的导入和扩展FileNotFoundException 的类GraphicsFileNotFoundException

在我的主 java 文件中,我尝试使用 getGraphicsFile 方法读取图形文件,该方法抛出 GraphicsFileNotFoundException

在 40 分钟试图找出如何捕捉这个异常之后,我的大脑被拉了一大堆。我尝试使用 try-catch 块并捕获 GraphicsFileNotFoundException 但我仍然收到错误

unreported exception GraphicsFileNotFoundException ; must be caught
   or declared to be thrown.



public void getGraphicsFile(String fileName) throws GraphicsFileNotFoundException {
    String graphics = "";
    Scanner getGraphics = null;
    try { 
      getGraphics = new Scanner(new File(fileName));
    }

    catch (GraphicsFileNotFoundException e){
      System.out.println("Error! File can't be found :/");
    }

【问题讨论】:

  • 你能举一个你用来尝试捕捉异常“GraphicsFileNotFoundExcepetion”的代码示例吗?从你在这里的解释来看,我没有看到任何明显的问题。这可能是代码中的语法或逻辑错误。
  • 是的,等一下
  • 哦,哈哈,我的意思是在实际问题中,使用代码格式化工具将其添加到问题中。每个人都更容易看到这种方式。
  • 我是新人 :( . 一秒
  • 您正试图在getGraphicsFile 内的一段代码中捕获GraphicsFileNotFoundException,但不会抛出它(因为 Scanner 构造函数根本不知道您的子类)。这不是您的问题的原因 - 您应该显示调用 getGraphicsFile 的主类。但这肯定是一个错误。而且你没有任何代码会抛出GraphicsFileNotFoundException

标签: java exception try-catch throw


【解决方案1】:

您需要正确扩展 FileNotFoundException 类或在 try 块内手动抛出异常。

假设这是一个作业(我不知道你为什么还需要专门扩展这个异常)你需要再看看你的 GraphicsFileNotFoundException 类并确保它做它需要的到。

要抛出异常,只需编写条件和throw 语句:

if(needToThrow) {
    throw new GraphicsFileNotFoundException();
}

要捕获异常,请用 try 块包围 throw 语句,然后紧跟 catch 块。

try {
    // code here
    if(needToThrow) {
        throw new GraphicsFileNotFoundException();
    }
}
catch(GraphicsFileNotFoundException e) {
    // handle the error (print stack trace or error message for example)
    e.printStackTrace(); // this is printing the stack trace
}

如果您还没有使用 Eclipse,我建议您使用它,因为很多时候它会提供围绕需要使用自动生成的 try catch 块捕获的 throw 语句。

【讨论】:

  • 谢谢布兰达蒙。刚要开始写这个。我认为这是他的问题。我也同意你的观点。
  • 哇,这很有意义。万分感谢!是的...我今天实际上尝试下载 Eclipse,但由于某种原因,它在我的计算机上找不到 Java 的位置。这是另一个问题,我很快就会处理。
  • @EmiliaClarke 提出问题,或直接私信我,我很乐意提供帮助。 Eclipse 是一个了不起的工具,几乎所有认真对待 java 的人都使用它或其他类似的 ide,例如 IntelliJ 或 NetBeans
猜你喜欢
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 2014-04-23
  • 1970-01-01
  • 2016-02-17
  • 1970-01-01
  • 2017-10-14
  • 2011-05-07
相关资源
最近更新 更多