繁体   English   中英

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

[英]Catching thrown exceptions with an Exception class I created

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 :/");
    }

您需要正确扩展FileNotFoundException类或手动在try块中引发异常。

假设这是一个赋值(我不确定为什么你还需要专门扩展这个异常),你需要再看一下你的GraphicsFileNotFoundException类,并确保它做了它需要的东西。

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

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

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

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,我建议使用Eclipse ,因为很多时候它会提供需要使用自动生成的try catch块捕获的环绕声抛出语句。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM