Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Besides your example which declares local fields outside the <code>try</code> block in order to be accessible inside the <code>catch</code> block, one very simple way of handling this is to dump the state of the class out in the <code>Exception</code> using the class's overridden <code>toString</code> method. Granted, this is only useful in <code>Class</code>es that maintain state. </p> <pre><code>try { setMyValue(someObject.getValue()); doSomething(getMyValue()); } catch (BadThingsHappenException bthe) { // consider this a RuntimeException wrapper class throw new UnhandledException(toString(), bthe); } </code></pre> <p>Your <code>toString()</code> would need to be overridden:</p> <pre><code>public String toString() { return super.toString() + "[myValue: " + getMyValue() +"]"; } </code></pre> <p><strong>edit:</strong></p> <p>another idea:</p> <p>You could maintain state in a <a href="http://java.sun.com/javase/6/docs/api/java/lang/ThreadLocal.html" rel="nofollow noreferrer"><code>ThreadLocal</code></a> debug context. Suppose you create a class called <code>MyDebugUtils</code> which holds a <code>ThreadLocal</code> that contains a Map per Thread. You allow for static access to this <code>ThreadLocal</code> and maintenance methods (ie, to clear the context when your debugging is finished). </p> <p>The interface could be:</p> <pre><code>public static void setValue(Object key, Object value) public static void clearContext() public static String getContextString() </code></pre> <p>and in our example:</p> <pre><code>try { MyDebugUtils.setValue("someObeject.value", someObject.getValue()); doSomething(someObject.getValue()); } catch (BadThingsHappenException bthe) { // consider this a RuntimeException wrapper class throw new UnhandledException(MyDebugUtils.getContextString(), bthe); } finally { MyDebugUtils.clearContext(); } </code></pre> <p>There might be some issues that you would want to iron out, such as handling cases where your <code>doSomething</code> method also contains a <code>try/catch/finally</code> set that clears the debug context. This could be handled by allowing for finer granularity in the context Map than just the Thread in the process:</p> <pre><code>public static void setValue(Object contextID, Object key, Object value) public static void clearContext(Object contextID) public static String getContextString(Object contextID) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload