I am trying to write a valid error message for when certain lists/calls return empty, without having to remove 'void' from my class, what is the best practice/syntax for this task? I know I can remove void from my class and create a variable then return it (return r; where r is a string failure message) but there has to be a better way to do so, right?

  • What is the context for your error handling? For example: An Apex trigger, a Visualforce page, a Lighting component. – Marty C. Nov 11 '14 at 20:02

Apex supports custom exceptions. If it really is an error then you could throw your own exception with the required message. You are then free to explicitly catch the error and handle it as required.


public void someMethod(List<string> inputList) {
    // ... code that would usually populate the list
    if(inputList.size() == 0) {
        throw new ListEmptyException('The list is empty');

public class ListEmptyException extends Exception {}

You can also use assertions, but these are better suited for test cases.

System.assertNotEqual(0, inputList.size(), 'The input list should not be empty');

I think your question is how to handle errors that happen during webservice calls out, so with that being said I answered a question before that creates a new exception record using a custom object that allows me to keep track of errors, using this pattern is probably the most effective way to keep track of service call outs.. So if you wanted to you could combine this with Daniels answer also

Which of these error handling patterns is more efficient?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.