Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Yes, MadMurf points out the most important difference: reachability checking at compile-time. The standard idiom would catch something like this and rightfully prevent it from compiling:</p> <pre><code> try { } catch (IndexOutOfBoundsException iooe) { } catch (ArrayIndexOutOfBoundsException aiooe) { } </code></pre> <p>The if/instanceof analog proposed in the original question would compile (which is NOT what you'd want because it's erroneous).</p> <p>The reason why the standard idiom catches the error at compile time is given in <a href="http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.21" rel="noreferrer">JLS 14.21 Unreachable Statements</a>.</p> <blockquote> <ul> <li>A catch block C is reachable iff both of the following are true: <ul> <li>[...]</li> <li>There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.</li> </ul></li> </ul> </blockquote> <p>To further illustrate the point, the following compiles:</p> <pre><code> try { } catch (Exception e) { if (e instanceof Exception) { } else if (e instanceof Exception) { } } </code></pre> <p>As you can see, this "pokemon catching" idiom is much harder to maintain because it circumvents some of the compile-time reachability check enforced in the standard idiom.</p> <p>To make the point even more clear, whether you did it on purpose or not, you actually rearranged the order in which you checked the exceptions in your original question, a fact that could have easily been missed by others. If SubSubException is a subclass of SubException, the second if condition will NEVER be evaluated, and its body is effectively unreachable code.</p> <p>The if/instanceof approach is VERY prone to mistakes.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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