How do you write test class if the exception has been thrown

   public class UserService{
        public class UserServiceException extends Exception{}
        public static Contact createUser(Contact applicant, Id accountid){
           throw new UserServiceException('Contact firstName is null');
        return applicant;

1 Answer 1


In a nutshell, by using a try/catch in your unit test.

static void testExceptionThrown() {
    // We need something to detect whether the exception has been thrown
    //   (and caught by this test) or not
    Boolean exceptionCaught = false;

    } catch(MyException e) {
        // Catching specific exceptions is generally better practice.
        // That's doubly true for unit tests.
        // So don't write "catch(Exception e)" (a.k.a. the "pokemon" catch)
        exceptionCaught = true;

    // Assert that you caught the exception (because assertions are what make
    //   tests useful to us developers)
    System.Assert.isTrue(exceptionCaught, 'Didn\'t catch the expected exception');

  • 1
    I agree (obviously) that Exception should be avoided, it would probably be acceptable in the case where you assert instanceof. IMO that's more informative than Assert.isTrue.
    – Adrian Larson
    Mar 16, 2023 at 3:24
  • 1
    I like putting a Assert.fail('exception sb thrown') after the MyClass.myMethod(), then separate catches for the exception(s) I care about and an all other - avoids the Booleans
    – cropredy
    Mar 16, 2023 at 17:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .