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
OldDeadBugOldDeadBug 

Message from custom exception only displays after a Loop Break??

After reading through the Introduction to Exception Handling guide, I was able to construct a Custom Exception class..

 

public class QException extends Exception{}

 

 

..., and in the inside of a try{} catch{} statement I have:

 

 

try
{
   if (condition)
   {
       throw new QException();
   }
} catch (QException e)
{
   e.setMessage('Error Message')
   Apex.addMessages(e);
}

 

 

In this case, the error message shows up in the debug log, but not on the page. Also, the scipt continues to run after the catch statement - when I actually want to the script to stop and the message to be displayed to the Page. I thought that was the point of using a custom Exception - probably wrong about that.

 

Now if I put the entire try-catch statement into a for loop, I can use the break; statement to stop the script and display the message:

 

 

for (loop condition)
{
   
   try
   {
      if (condition)
      {
          throw new QException();
      }
   } catch (QException e)
   {
      e.setMessage('Error Message')
      Apex.addMessages(e);
      break;
   }
}

 

 

This works!

 

So it seems like I'm doing something wrong with the first example, with subsequent code running after the Exception is thrown, or else the loop/break process provides some additional code-stopping capability that I can take advantage of here. However, not all Exceptions happen in loops, and it seems silly to force one's code into a loop to be able to use the try/catch process for exceptions - which seems to be the tried and true method from what I've seen.

 

Also, adding an id to the PageMessages and reRendering (reRender="Messages") it doesn't seem to work either, but I'm probably doing that wrong as well.

 

Any replies, suggestions, explanations are appreciated.

 

 

 

 

aballardaballard

When you catch an exception, the code will continue execution after the try...catch... statement, unless you do something to prevent it continuing, like rethrowing the exception or throwing a different exception.  

 

break has no magic effect or special interaction with exceptions... it just breaks out of the loop.  You must have skipped some other processing as a result of that.