function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Katherine RoweKatherine Rowe 

Need an example of an unhandled exception

I need a trigger that will throw an unhandled exception. I'm new to writing triggers, can someone help me whip one up? I'm testing the emails that SF sends out to the last modified user on the trigger, when there is an unhandled exception.
 

It can be really simple. I just want to be able easily fire the trigger in SF and for it to throw an unhandled exception. 

Best Answer chosen by Katherine Rowe
pconpcon
You have to create a new exception type.  You cannot just throw a bare exception.  Also you'll want to verify that you actually threw the exception that you expecting, not just that something else broke in your test.  So for example:

TestUtils.cls
public class TestUtils {
    public static Boolean gotTestException = false;
    public static Boolean throwTestException = false;

    public static String TEST_EXCEPTION = 'This is a test exception';

    public class UnhandledException extends Exception {}
}

MyTrigger.trigger
trigger MyTrigger on Opportunity (before update) {
    try {
        if (Test.isRunningTest() && TestUtils.throwTestException) {
            throw new TestUtils.UnhandledException(TestUtils.TEST_EXCEPTION);
        }

        // Do stuff
    } catch (Exception e) {
        if (e.getMessage() == TestUtils.TEST_EXCEPTION) {
            TestUtils.gotTestException = true;
        }

        // Do more stuff
    }
}

MyTriggerTest.cls
@isTest
private class MyTriggerTest {
    static testMethod void exceptionTest() {
        Opportunity testOpp = new Opportunity(...);

        Test.startTest();

        TestUtils.throwTestException = true;
        insert testOpp;

        Test.stopTest();

        System.assert(TestUtils.gotTestException, 'We should have thrown and caught an exception');
    }
}

I know it seems a bit complicated, but I assure you it's worth the time and will make your code more robust in the long run.

All Answers

pconpcon
What I do in this case is I create a custom Exception that is not used anywhere and throw that.  You can see the try/catch here [1] and the implemntation of the unhandled exception here [2].  And then how to use it in your test here [3]

[1] http://pcon.github.io/presentations/testing/#exceptional-unknown-class-pre
[2] http://pcon.github.io/presentations/testing/#exceptional-unknown-class-post
[3] http://pcon.github.io/presentations/testing/#exceptional-unknown-test
Katherine RoweKatherine Rowe
pcon,

That was a little above me, and it seems to involve creating classes? I was envisioning somethign easier.

Can I not just write a trigger something like this? This is just pseudo code, I would need help writing this in apex that it would accept.
 
trigger testThrowException on Opportunity (before update) {
 
if ( Begins (Opportunity.Name, 'B')  {
    throw new exception(); }
 
Try{
if (Begins (Opportunity.Name, ‘C’) {
    throw new exception(); }
}

Catch{
    Display message “Good job, your code just caught an exception”;}
 
}


 
pconpcon
You have to create a new exception type.  You cannot just throw a bare exception.  Also you'll want to verify that you actually threw the exception that you expecting, not just that something else broke in your test.  So for example:

TestUtils.cls
public class TestUtils {
    public static Boolean gotTestException = false;
    public static Boolean throwTestException = false;

    public static String TEST_EXCEPTION = 'This is a test exception';

    public class UnhandledException extends Exception {}
}

MyTrigger.trigger
trigger MyTrigger on Opportunity (before update) {
    try {
        if (Test.isRunningTest() && TestUtils.throwTestException) {
            throw new TestUtils.UnhandledException(TestUtils.TEST_EXCEPTION);
        }

        // Do stuff
    } catch (Exception e) {
        if (e.getMessage() == TestUtils.TEST_EXCEPTION) {
            TestUtils.gotTestException = true;
        }

        // Do more stuff
    }
}

MyTriggerTest.cls
@isTest
private class MyTriggerTest {
    static testMethod void exceptionTest() {
        Opportunity testOpp = new Opportunity(...);

        Test.startTest();

        TestUtils.throwTestException = true;
        insert testOpp;

        Test.stopTest();

        System.assert(TestUtils.gotTestException, 'We should have thrown and caught an exception');
    }
}

I know it seems a bit complicated, but I assure you it's worth the time and will make your code more robust in the long run.
This was selected as the best answer
Katherine RoweKatherine Rowe

Ok thanks! I got it working.

Question. I see the unhandled exception being display in red on the screen. But I'm only ocassionally get the emails that says an unhandled exception has happened. It kind of seems like it is sending me the email the first time that trigger causes an unhandled exception, but not anymore after that.
 

Why aren't I getting the emails every time the unhandled exception occurs? My trigger should have only run about 5 or 6 times today, so that doesn't sound like I'm hitting any kind of limit?

pconpcon
Great! If you could please choose a "best answer" so that this question can be removed from the unresolved queue and so others may easily find the answer.

As for why you aren't getting the email everytime, I've seen the same behavior and I do wonder if it has something to do with how frequently the issue happens.  IE only sending the same error email once a day.  It might be worth trying this new feature [1] that was introduced in Winter '16 and configuring the Exception mails to see if it changes anything.

[1] http://releasenotes.docs.salesforce.com/en-us/winter16/release-notes/rn_apex_exception_emails.htm
Katherine RoweKatherine Rowe

Ok, I had read other posts where users had the same problem, not getting the emails every time. I guess that's the current behavior for everyone then.

I just tried adding myself to the Apex Exception Email list, but that doesn't seem to fix the "dont' receive emails everytime" problem.

Shiju Thomas.Shiju Thomas.
Hello All,

Just wanted to know if we have a way of catching the unhandled exception (This is just one occurrence.). 
We are can easily recreate this issue by trying to set the password of an inactive user.

Our approach is to deactivate the user if he does not login to the system for a period of 6 months.
So, once the deactivated user tries to login to his/her customer portal and tries to reset his/her password in order to login, we get the exception being caught.

Code to recreate the issue.

Step-1: Find an inactive user.
Step-2: Pass the user id and new password to the code as "System.setPassword('userId','newPassword');"

Though we have a workaround for this solution, I just wanted to know if there are any ways of finding/trapping such issue through a try-catch or some other mechanism?