JAVA finally字句的异常丢失和返回值覆盖解析
JAVA finally字句的异常丢失和返回值覆盖解析
Java虚拟机在每个try语句块和与其相关的catch子句的结尾
处都会“调用”finally子句的子例程。实际上,finally子句在方法内部的表现很象“微型子例程”。finally子句正常结束后-指的是finally子句中最后一条语句正常执行完毕,不包括抛出异常,或执行return、continue、break等情况,隶属于这个finally子句的微型子例程执行“返回”操作。程序在第一次调用微型子例程的地方继续执行后面的语句。
finally“微型子例程”不等同于方法函数的调用,finally子句都是在同一个栈内执行的,微型子例程的“返回”操作也不会涉及到方法退栈,仅仅是使程序计数器pc跳转到同一个方法的一个不同的位置继续执行。
一 异常丢失
public static void exceptionLost()
{
try
{
try
{
throw new Exception( "exception in try" );
}
finally
{
throw new Exception( "exception in finally" );
}
}
catch( Exception e )
{
System.out.println( e );
}
}
exceptionLost()的输出结果是“exception in finally”,而不是try块中抛出的异常,这是JAVA异常机制的一个瑕疵-异常丢失。
在字节码中,throw语句不是原子性操作。在较老的JDK中,exceptionLost()中try块的throw语句分解为几步操作:
1) 把Exception("exception in try")对象引用存储到一个局部变量中
astore_2 // pop the reference to the thrown exception, store into local variable 2
2) 调用finally微型子程序
3) 把局部变量中的Exception("exception in try")对象引用push到操作数栈顶,然后抛出异常
aload_2 // push the reference to the thrown exception from local variable 2
athrow // throw the exception
如果finally通过break、return、continue,或者抛出异常而退出,那么上面的第3步就不会执行。
在JDK1.6中,通过字节码我们可以看到,finally子句作为一种特殊的catch来实现的,下面是exceptionLost()方法的异常表:
Exception table:
from to target type
0 10 10 any
相关文档:
jar -cvf name.jar *.*(打包此目录下所有文件)
jar -cvf name.jar filename(打包此目录下单个文件helloWorld.java或文件夹)
jar -cvf name.jar filename1 filename2....(打包此目录下多个文件或文件夹)
参考: jar ......
参考代码:
class SuperClass {
private int n;
SuperClass() {
System.out.println("SuperClass()");
}
SuperClass(int n) {
System.out.println("SuperClass(" + n + ")");
this.n = n;
}
}
class SubClass extends SuperClass {
private int n ......
在java代码中经常有读取外部资源的要求:如配置文件等等,通常会把配置文件放在classpath下或者在web项目中放在web-inf下.
1.从当前的工作目录中读取:
try {
BufferedReader in = new BufferedReader(new InputStreamRea ......
学.NET就好比和爹妈一起出门,啥事都不用愁,因为爹妈都给你操心着了。
学Java就像自己出门,你要睁大眼睛看清周围的世界,并决定你自己的方向;
必要的时候,你要脱离一切束缚,自己搞一套框架来适应特殊需求。
在Java的世界里,有着形形色色的开源产品和框架。
它们就好像你在异 ......
1. ActionForm中添加属性,FormFile类型对象。
private FormFile upLoadFile;
public FormFile getUpLoadFile() {
return upLoadFile;
}
public void setUpLoadFile(FormFile upLoadFile) {
this.upLoadFile = upLoadFile;
}
2. Action 中增加修改方法。
public ActionForward save(ActionMapping mapping, Action ......