这个问题是自己在写try-catch语句中发现的中的时发现的。关于return在try-catch外写还是不写的问题
(注:关于return在finally中的问题我在讨论异常的那篇博客里示例的很清楚了,如果是关于这个地方有疑问的朋友可以去翻翻我之前的的博客)
http://blog.youkuaiyun.com/qq_32691345/article/details/75949221
(我之前写的java异常的博客的地址)
先说明一下问题
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
test();
}
public static int test(){
try {
FileInputStream fis=new FileInputStream("demo.txt");
return 1;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
在这里编译器会提醒在test方法上提醒报:This method must return a result of type int。
代码补全后:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
test();
}
public static int test(){
try {
FileInputStream fis=new FileInputStream("demo.txt");
return 1;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return 0;
}
}
分析一下原因:因为第一段代码的return是在try-catch中执行的,try会尝试着执行try中的代码。当遇见异常时跳出try块,执行catch块。光在try中写return,如果出现异常,这个方法就没有返回值了。所以必须在外面(try-catch块外)写return 或者在catch中写return。
知道了上面的内容我们再来看看后面这个问题
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
}
public static int test() throws Exception{
try {
FileInputStream fis=new FileInputStream("demo.txt");
return 1;
} catch (FileNotFoundException e) {
throw new Exception("出错了",e);
}
return 0;
}
}
上面这段代码中,编译器又会在return 0;处提醒去掉:Unreachable code(执行不到的代码)。
这是为什么呢?在最开始的代码中提醒要加上return而在现在的代码中却提醒删去。
我们再来分析一下:try中未出现异常,则正常返回,如果出现异常,跳出try语句执行catch块,在catch中这里与最开始的catch不同,前者是将异常打印,后者是将异常抛出。这两者有着很大的区别:前者打印异常后继续执行程序。而在catch中抛出,交给上层去处理,这样会使得test()方法中断,后面的不会执行(即方法不再需要返回值,都没执行完要什么返回值!),所以在try-catch块外加return就显得没有意义:执行不到的代码。所以需要删除。
正确代码:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
try {
test();
} catch (Exception e) {
e.printStackTrace();
}
}
public static int test() throws Exception{
try {
FileInputStream fis=new FileInputStream("demo.txt");
return 1;
} catch (FileNotFoundException e) {
throw new Exception("出错了",e);
}
}
}