今天研究开源代码时遇到一些有关异常处理的部分,基本机构如下
public class ExceptionText {
public static void main(String args[]) {
try {
myMethod();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String myMethod()throws Exception{
try {
return "str";
} catch (Exception e) {
// TODO: handle exception
throw e;
}
}
}
如果myMethod()写成
public static String myMethod(){
try {
return "str";
} catch (Exception e) {
// TODO: handle exception
}
}
会报This method must return a result of type String语法错误,容易理解,因为发生异常后异常被在本方法中处理,调用这个方法的地方就得不到任何返回值,语法上行不通。
所以在catch块中将得到Exception实例抛出,这样即使myMethod()方法执行发生异常也会保证返回了一些东西,main方法中调用此方法的地方加上try..catch 块就捕获了此异常,根据语法规范继续执行。