[英]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.