Java 即使在调用方法中添加了try-catch-finally块,在main中也会出现编译错误
我试图运行下面的代码,但编译错误为“Unhandled exception type FileNotFoundException”,据我所知,这不应该发生,因为在调用方法中添加了try-catch和finally块Java 即使在调用方法中添加了try-catch-finally块,在main中也会出现编译错误,java,exception,Java,Exception,我试图运行下面的代码,但编译错误为“Unhandled exception type FileNotFoundException”,据我所知,这不应该发生,因为在调用方法中添加了try-catch和finally块 import java.io.FileInputStream; import java.io.FileNotFoundException; public class Test { public static void main(String[] args) {
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test
{
public static void main(String[] args)
{
myMethod();
}
public static void myMethod() throws FileNotFoundException
{
try
{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e)
{
System.out.println("in the catch block");
throw e;
}
finally
{
System.out.println("in the finally block");
}
}
}
从
myMethod
签名中删除throws FileNotFoundException
(然后需要从catch
块中删除throw e;
)
或,在main
方法中添加一个try
和catch
(用于处理您指示的myMethod
可以抛出的FileNotFoundException
)
或,将抛出FileNotFoundException
添加到main
的签名中(正如Andreas在评论中指出的)
简而言之,编译器将不允许您拥有包含未处理的已检查异常的代码路径。Remove
从myMethod
签名中抛出FileNotFoundException
(然后您需要从catch
块中移除throw e;
)
或,在main
方法中添加一个try
和catch
(用于处理您指示的myMethod
可以抛出的FileNotFoundException
)
或,将抛出FileNotFoundException
添加到main
的签名中(正如Andreas在评论中指出的)
简而言之,编译器将不允许您拥有未处理的已检查异常的代码路径。在
catch
块中,一旦捕捉到异常,您将再次抛出该异常。如果您真的想在捕获它之后从myMethod()
抛出它,只需在main方法中添加另一个try-catch即可
public static void main(String[] args){
try{
myMethod();
}catch(FileNotFoundException e){
System.out.println("catch block in main");
}
}
或者,如果您只想在myMethod()
中捕获异常
,请不要将其抛出
try{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e){
System.out.println("in the catch block");
}
finally{
System.out.println("in the finally block");
}
您可以在下面的问题中阅读有关重新抛出异常的更多信息
在
catch
块中,一旦捕获到异常,您将再次抛出该异常。如果您真的想在捕获它之后从myMethod()
抛出它,只需在main方法中添加另一个try-catch即可
public static void main(String[] args){
try{
myMethod();
}catch(FileNotFoundException e){
System.out.println("catch block in main");
}
}
或者,如果您只想在myMethod()
中捕获异常
,请不要将其抛出
try{
System.out.println("In the try block");
FileInputStream fis = new FileInputStream("file.txt");
}
catch(Exception e){
System.out.println("in the catch block");
}
finally{
System.out.println("in the finally block");
}
您可以在下面的问题中阅读有关重新抛出异常的更多信息
您正在重新引发异常,因此留下未处理的异常。最简单的解决方案:只需将抛出FileNotFoundException
添加到main()
。您正在重新引发异常,因此留下未处理的异常。最简单的解决方案:只需将抛出FileNotFoundException
添加到main()
。谢谢,所以是重新抛出异常的问题,已经捕获到了。不完全是这样。这就是您声明您的myMethod()
以抛出FileNotFoundException
的问题。只要您这样声明您的方法,即使您没有在myMethod
的catch块中重新调用,您仍然需要在main
中捕获,为什么不将抛出FileNotFoundException
添加到main()
?无需在catch
中添加代码,也无需在main()
中打印stacktrace,因为Java将为您执行此操作。谢谢,所以这是重新引发已捕获的异常的问题。不完全是这样。这就是您声明您的myMethod()
以抛出FileNotFoundException
的问题。只要您这样声明您的方法,即使您没有在myMethod
的catch块中重新调用,您仍然需要在main
中捕获,为什么不将抛出FileNotFoundException
添加到main()
?无需在catch
中添加代码,并在main()
中打印stacktrace,因为Java将为您完成这项工作。