title: writing a JUnit Test case for custom checked exception in Java?
body: <p>I am writing a test case for my class that has methods which throw exceptions (both checked and runtime). I have tried different possible ways of testing as suggested in this <a href="https://stackoverflow.com/questions/156503/how-do-you-assert-that-a-certain-exception-is-thrown-in-junit-4-tests/7927418#7927418">link.</a>. It appears they seem to work only for runtime exceptions. for Checked exceptions, I need to do a try/catch/assert as shown in the code below. Is there any alternatives to try/catch/assert/. you will notice that <code>testmethod2() and testmethod2_1()</code> shows compile error but <code>testmethod2_2()</code> does not show compile error which uses try/catch.</p>
  
  <pre><code>class MyException extends Exception {
  
      public MyException(String message){
          super(message);
      }
  }
  
  
  public class UsualStuff {
  
      public void method1(int i) throws IllegalArgumentException{
          if (i&lt;0)
             throw new IllegalArgumentException("value cannot be negative");
          System.out.println("The positive value is " + i );
      }
  
      public void method2(int i) throws MyException {
          if (i&lt;10)
              throw new MyException("value is less than 10");
          System.out.println("The value is "+ i);
      }
  
      }
  </code></pre>
  
  <p>Test class:</p>
  
  <pre><code>import static org.junit.Assert.*;
  
  import org.junit.Before;
  import org.junit.Rule;
  import org.junit.Test;
  import org.junit.rules.ExpectedException;
  
  
  public class UsualStuffTest {
  
      private UsualStuff u;
  
      @Before
      public void setUp() throws Exception {
          u = new UsualStuff();
      }
  
      @Rule
      public ExpectedException exception = ExpectedException.none();
  
      @Test(expected = IllegalArgumentException.class)
      public void testMethod1() {
          u.method1(-1);
      }
  
      @Test(expected = MyException.class)
      public void testMethod2() {
          u.method2(9);
      }
  
      @Test
      public void testMethod2_1(){
          exception.expect(MyException.class);
          u.method2(3);
      }
  
      public void testMethod2_3(){
          try {
              u.method2(5);
          } catch (MyException e) {
              assertEquals(e.getMessage(), "value is less than 10") ;
          }
      }
  }
  </code></pre>