使用我创建的 Exception class 捕获抛出的异常

Catching thrown exceptions with an Exception class I created

GraphicsFileNotFoundException.java 中,我所拥有的只是 FileNotFoundException 的导入和扩展 FileNotFoundException 的 class GraphicsFileNotFoundException

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

我花了整整 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 :/");
    }

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

假设这是一个作业(我不确定为什么你还需要专门扩展这个例外)你需要再看看你的 GraphicsFileNotFoundException class 和确保它执行所需的操作。

要抛出异常,只需写下您的条件和 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 块捕获的抛出语句。