2afcef188c89e25c0192151c2739d3f34d26628a
[org.ibex.core.git] / src / org / ibex / js / JSExn.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL] 
2 package org.ibex.js; 
3
4 import org.ibex.util.*; 
5 import java.io.*;
6
7 /** An exception which can be thrown and caught by JavaScript code */
8 public class JSExn extends Exception { 
9     private Vec backtrace = new Vec();
10     private JS js; 
11     public JSExn(String s) { this(JS.S(s)); }
12     public JSExn(JS js) { this(js,null); }
13     public JSExn(JS js, Interpreter cx) { this.js = js; fill(cx); }
14     
15     private void fill(Interpreter cx) {
16         if(cx == null) cx = Interpreter.current();
17         if(cx == null) return;
18         addBacktrace(cx.f.sourceName + ":" + cx.f.line[cx.pc]);
19         cx.stack.backtrace(this);
20     }
21     public void printStackTrace() { printStackTrace(System.err); }
22     public void printStackTrace(PrintWriter pw) {
23         for(int i=0; i<backtrace.size(); i++) pw.println("    at " + (String) backtrace.elementAt(i));
24         super.printStackTrace(pw);
25     }
26     public void printStackTrace(PrintStream ps) {
27         for(int i=0; i<backtrace.size(); i++) ps.println("    at " + (String) backtrace.elementAt(i));
28         super.printStackTrace(ps);
29     }
30     public String toString() { return "JSExn: " + JS.debugToString(js); }
31     public String getMessage() { return toString(); }
32     public JS getObject() { return js; } 
33     
34     void addBacktrace(String line) { backtrace.addElement(line); }
35     
36     public static class Wrapper extends RuntimeException {
37         public final JSExn e;
38         public Wrapper(JSExn e) { this.e = e; }
39         public JSExn refill() {
40             e.addBacktrace("[foreign code]");
41             e.fill(null);
42             return e;
43         }
44     }
45     
46     public static class IO extends JSExn {
47         public IO(java.io.IOException ioe) {
48             super("ibex.io: " + ioe.toString());
49             JS.warn(ioe);
50         }
51     }
52