1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
/*****************************************************************************
* *
* This file is part of the BeanShell Java Scripting distribution. *
* Documentation and updates may be found at http://www.beanshell.org/ *
* *
* BeanShell is distributed under the terms of the LGPL: *
* GNU Library Public License http://www.gnu.org/copyleft/lgpl.html *
* *
* Patrick Niemeyer (pat@pat.net) *
* Author of Exploring Java, O'Reilly & Associates *
* http://www.pat.net/~pat/ *
* *
*****************************************************************************/
package bsh;
import java.util.Vector;
class BSHTryStatement extends SimpleNode
{
BSHTryStatement(int id)
{
super(id);
}
public Object eval(NameSpace namespace, Interpreter interpreter) throws EvalError
{
BSHBlock tryBlock = ((BSHBlock)jjtGetChild(0));
Vector catchParams = new Vector();
Vector catchBlocks = new Vector();
int nchild = jjtGetNumChildren();
Node node = null;
int i=1;
while((i < nchild) && ((node = jjtGetChild(i++)) instanceof BSHFormalParameter))
{
catchParams.addElement(node);
catchBlocks.addElement(jjtGetChild(i++));
node = null;
}
// finaly block
BSHBlock finallyBlock = null;
if(node != null)
finallyBlock = (BSHBlock)node;
// Why both of these?
TargetError target = null;
Throwable thrown = null;
Object ret = null;
// Evaluate the contents of the try { } block
try {
ret = tryBlock.eval(namespace, interpreter);
}
catch(TargetError e) {
target = e;
}
if ( target != null )
thrown = target.getTarget();
if(thrown != null) // we have an exception, find a catch
{
int n = catchParams.size();
for(i=0; i<n; i++)
{
// get catch block
BSHFormalParameter fp = (BSHFormalParameter)catchParams.elementAt(i);
fp.eval(namespace, interpreter);
// does it match?
try {
thrown = (Throwable)NameSpace.checkAssignableFrom(
thrown, fp.type);
} catch(EvalError e) {
continue;
}
// Found match, execute catch block
BSHBlock cb = (BSHBlock)(catchBlocks.elementAt(i));
namespace.setTypedVariable(fp.name, fp.type, thrown,false);
ret = cb.eval( namespace, interpreter );
target = null; // handled target
break;
}
}
// evaluate finally block
if(finallyBlock != null)
ret = finallyBlock.eval(namespace, interpreter);
// exception fell through, throw it upward...
if(target != null)
throw target;
if(ret instanceof ReturnControl)
return ret;
else
return Primitive.VOID;
}
}
|