title: How to use Hamcrest in Java to test for a exception?
body: <p>How do I use Hamcrest to test for an exception?  According to a comment in <a href="https://code.google.com/p/hamcrest/wiki/Tutorial" rel="noreferrer">https://code.google.com/p/hamcrest/wiki/Tutorial</a>, "Exception handling is provided by Junit 4 using the expected attribute."  </p>
  
  <p>So I tried this and found that it worked:</p>
  
  <pre><code>public class MyObjectifyUtilTest {
  
      @Test
      public void shouldFindFieldByName() throws MyObjectifyNoSuchFieldException {
          String fieldName = "status";
          String field = MyObjectifyUtil.getField(DownloadTask.class, fieldName);
          assertThat(field, equalTo(fieldName));
      }
  
      @Test(expected=MyObjectifyNoSuchFieldException.class)
      public void shouldThrowExceptionBecauseFieldDoesNotExist() throws MyObjectifyNoSuchFieldException {
          String fieldName = "someMissingField";
          String field = MyObjectifyUtil.getField(DownloadTask.class, fieldName);
          assertThat(field, equalTo(fieldName));      
      }
  
  }
  </code></pre>
  
  <p>Does Hamcrest provide any additional functionality above and beyond the <code>@Test(expected=...)</code> annotation from JUnit?</p>
  
  <p>While someone asked about this in Groovy (<a href="https://stackoverflow.com/questions/19256175/how-to-use-hamcrest-to-test-for-exception">How to use Hamcrest to test for exception?</a>), my question is for unit tests written in Java.</p>