[英]Catching thrown exceptions with an Exception class I created
In GraphicsFileNotFoundException.java
all I have is an import of FileNotFoundException
and the class GraphicsFileNotFoundException
which extends FileNotFoundException
. 在GraphicsFileNotFoundException.java
我所有的都是FileNotFoundException
的导入和扩展FileNotFoundException
GraphicsFileNotFoundException
类。
In my main java file, I'm trying to read in a graphics file with the method getGraphicsFile
which throws GraphicsFileNotFoundException
. 在我的主java文件中,我试图用图形文件读取getGraphicsFile
方法,该方法抛出GraphicsFileNotFoundException
。
My brain is pooped after a good 40 minutes trying to find out how to catch this exception. 经过40分钟的努力,我的大脑陷入困境,试图找出如何捕获这个异常。 I've tried using a try-catch block and catching GraphicsFileNotFoundException
but I still get the error 我已经尝试使用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 :/");
}
You need to either properly extend the FileNotFoundException
class or manually throw an exception inside your try
block. 您需要正确扩展FileNotFoundException
类或手动在try
块中引发异常。
Assuming this is for an assignment (I'm not sure why else you'd need to specifically extend this exception) you'll need to take another look at your GraphicsFileNotFoundException
class and make sure that it does what it needs to. 假设这是一个赋值(我不确定为什么你还需要专门扩展这个异常),你需要再看一下你的GraphicsFileNotFoundException
类,并确保它做了它需要的东西。
To throw an exception, simply write your condition and the throw
statement: 要抛出异常,只需编写条件和throw
语句:
if(needToThrow) {
throw new GraphicsFileNotFoundException();
}
To catch an exception, surround the throw statement with a try
block immediately followed by a catch
block. 要捕获异常,请使用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
}
I recommend using Eclipse if you aren't already because many times it will offer to surround throw statements that need to be caught with a automatically generated try
catch
block. 如果您还没有使用Eclipse,我建议使用Eclipse ,因为很多时候它会提供需要使用自动生成的try
catch
块捕获的环绕声抛出语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.