Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here is a simple example of how to use the exception:</p> <pre><code>class IntegerExceptionTest { public static void main(String[] args) { try { throw new IntegerException(42); } catch (IntegerException e) { assert e.getValue() == 42; } } } </code></pre> <p>The body of the TRy statement throws the exception with a given value, which is caught by the catch clause.</p> <p>In contrast, the following definition of a new exception is prohibited, because it creates a parameterized type:</p> <pre><code>class ParametricException&lt;T&gt; extends Exception { // compile-time error private final T value; public ParametricException(T value) { this.value = value; } public T getValue() { return value; } } </code></pre> <p>An attempt to compile the above reports an error:</p> <pre><code>% javac ParametricException.java ParametricException.java:1: a generic class may not extend java.lang.Throwable class ParametricException&lt;T&gt; extends Exception { // compile-time error ^ 1 error </code></pre> <p>This restriction is sensible because almost any attempt to catch such an exception must fail, because the type is not reifiable. One might expect a typical use of the exception to be something like the following:</p> <pre><code>class ParametricExceptionTest { public static void main(String[] args) { try { throw new ParametricException&lt;Integer&gt;(42); } catch (ParametricException&lt;Integer&gt; e) { // compile-time error assert e.getValue()==42; } } } </code></pre> <p>This is not permitted, because the type in the catch clause is not reifiable. At the time of this writing, the Sun compiler reports a cascade of syntax errors in such a case:</p> <pre><code>% javac ParametricExceptionTest.java ParametricExceptionTest.java:5: &lt;identifier&gt; expected } catch (ParametricException&lt;Integer&gt; e) { ^ ParametricExceptionTest.java:8: ')' expected } ^ ParametricExceptionTest.java:9: '}' expected } ^ 3 errors </code></pre> <p>Because exceptions cannot be parametric, the syntax is restricted so that the type must be written as an identifier, with no following parameter.</p>
 

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