title: Java if vs. try/catch overhead
body: <p>Is there any overhead in Java for using a <strong>try/catch</strong> block, as opposed to an <strong>if block</strong> (assuming that the enclosed code otherwise does not request so)?</p>
  
  <p>For example, take the following two simple implementations of a "safe trim" method for strings:</p>
  
  <pre><code>public String tryTrim(String raw) {
      try {
          return raw.trim();
      } catch (Exception e) {
      }
      return null;
  }
  
  public String ifTrim(String raw) {
      if (raw == null) {
          return null;
      }
      return raw.trim();
  }
  </code></pre>
  
  <p>If the <code>raw</code> input is only rarely <code>null</code>, <strong>is there any performance difference</strong> between the two methods?</p>
  
  <p>Furthermore, <strong>is it a good programming pattern</strong> to use the <code>tryTrim()</code> approach for simplifying the layout of code, especially when many <strong>if blocks</strong> checking rare error conditions can be avoided by enclosing the code in one try/catch block?</p>
  
  <p>For example, it is a common case to have a method with <code>N parameters</code>, which uses <code>M &lt;= N</code> of them near its start, failing quickly and deterministically if any such parameter is "invalid" (e.g., a null or empty string), without affecting the rest of the code.</p>
  
  <p>In such cases, instead of having to write <code>k * M</code> <strong>if blocks</strong> (where <code>k</code> is the average number of checks per parameter, e.g. <code>k = 2</code> for null or empty strings), a <strong>try/catch</strong> block would significantly shorten the code and a 1-2 line comment could be used to explicitly note the "unconventional" logic.</p>
  
  <p>Such a pattern would also speed up the method, especially if the error conditions occur rarely, and it would do so without compromising program safety (assuming that the error conditions are "normal", e.g. as in a string processing method where null or empty values are acceptable, albeit seldom in presence).</p>