package kawa.lang;
import gnu.mapping.*;

/** Used to implement catch/throw named handlers as in Guile:
  * (catch 'key (lambda () ... (throw 'key ARGS ...) ...)
  *             (lambda (KEY ARGS ...) HANDLER))
  */

public class NamedException extends RuntimeException
{
  String name;
  // Arguments to throw (including, for efficiency, the name).
  Object[] args;

  public NamedException (String name, Object[] args)
  {
    this.name = name;
    this.args = args;
  }

  public void checkMatch (Object key)
  {
    if (key != this.name && key != Boolean.TRUE)
      throw this;
  }

  public Object applyHandler (Object key, Procedure handler) throws Throwable
  {
    checkMatch(key);
    return handler.applyN(args);
  }

  public String toString()
  {
    StringBuffer buf = new StringBuffer();
    buf.append("#<ERROR");
    int i = 0;
    int len = args.length;
    // Skip initial 'misc-error as generated by the error procedure.
    if (len > 1 && args[0] == "misc-error")
      i++;
    for ( ;  i < len;  i++)
      {
	buf.append(' ');
	buf.append(args[i]);
      }
    buf.append(">");
    return buf.toString();
  }
}
