title: Java exception handling (example with json)
body: <p>First, I would like to say I'm sorry for such an ambiguous title... </p>
  
  <p>I would like to know how to handle exceptions in the following scenario...
  I have a Struts action that receives a string from a EJB:</p>
  
  <pre><code>try{       
    JSONObject data = new JSONObject(result);   //result is String 
    String gatewayId = data.getString("gatewayId");
    session.setAttribute("gatewayId", gatewayId);
  }catch(Exception e){
    System.out.println(e.getMessage());
  }
  </code></pre>
  
  <p><strong>EDIT</strong>
  Imports are:</p>
  
  <pre><code>import org.apache.struts2.json.*;
  import org.json.*;
  </code></pre>
  
  <p>In case A json is:</p>
  
  <pre><code>{"gatewayId":100, "mask":4}
  </code></pre>
  
  <p>In case B json is:</p>
  
  <pre><code>{"success":false, "errorDesc":"bla bla"}
  </code></pre>
  
  <p>If the  <strong>gatewayId</strong> is in the JSON I have no problem, but the problem is that the JSON received from EJB can (but doesn't have to) have that key:value pair.</p>
  
  <p>If there was a <strong>Boolean JsonObject.hasString()</strong> method I would have no exceptions thanks to checking the existance of the string first in if/else if statements, but this way I can't avoid exceptions...</p>
  
  <p>The first thing I thought I could do was to have different catch blocks depending on the exception type, but it seems that all exceptions are of generic <strong>JSONException</strong> type and also I shouldn't put any JSON treating code in the catch block because that code could also be throwing it's exceptions.</p>
  
  <p>Please, have in mind that I'm not looking for the exact solution of my JSON problem here, but rather a general explanation of how to solve this kind of problems when you don't have functions that help you avoid having exceptions...</p>
  
  <p>I hope my question makes sense....</p>