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

Java 使用我创建的异常类捕获抛出的异常,java,exception,try-catch,throw,Java,Exception,Try Catch,Throw,在GraphicsFileNotFoundException.java中,我只有导入FileNotFoundException和扩展FileNotFoundException的类GraphicsFileNotFoundException 在我的主java文件中,我尝试使用方法getGraphicsFile读入图形文件,该方法抛出GraphicsFileNotFoundException 我花了整整40分钟的时间试图找出如何抓住这个异常,我的大脑都快崩溃了。我尝试过使用try-catch块并捕获G

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
块中手动抛出异常

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
}
假设这是一个作业(我不确定为什么还需要专门扩展此异常),您需要再次查看
GraphicsFileNotFoundException
类,并确保它执行所需的操作

要引发异常,只需编写您的条件和
throw
语句:

if(needToThrow) {
    throw new GraphicsFileNotFoundException();
}
若要捕获异常,请在throw语句周围加一个
try
块,后面紧跟一个
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
}

我建议您使用if-you-not,因为很多时候,它会提供一个自动生成的
try
catch
块来包围需要捕获的抛出语句。

您能举一个代码示例来尝试捕获异常“GraphicsFileNotFoundExcepetion”?。根据你在这里的解释,我看不出有什么明显的问题。这可能是代码中的语法或逻辑错误。是的,等一下哦,哈哈,我在实际问题中的意思是,使用代码格式化工具将其添加到问题中。对每个人来说,这样看比较容易。我是新来的:(.一秒钟后,您试图在
getGraphicsFile
中的一段代码中捕获
GraphicsFileNotFoundException
,该代码没有抛出它(因为Scanner构造函数根本不知道您的子类)。这不是问题的原因-您应该显示调用
getGraphicsFile
的主类。但这肯定是一个错误。而且您没有任何代码抛出
GraphicsFileNotFoundException
。感谢brandaemon。我正要开始编写这个。我认为这是他的问题。我也同意您在eclipse上的看法.哇,这很有道理。非常感谢!是的……我今天确实试过下载Eclipse,但由于某种原因,它在我的计算机上找不到Java的位置。这是一个我很快就会解决的问题。@EmiliaClarke打开一个问题,或者直接pm我,我很乐意提供帮助。Eclipse是一个了不起的工具,几乎每个人ho对java使用它或类似IntelliJ或NetBeans的ide是认真的
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
}