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
dawnzdydawnzdy 

How to display error msg on visualforce page through catch {}

Hi Everyone,
 
   I am trying to display error msg on visualforce page when a var may cause exception.          Using <ApexPages.addMessage>  in the controller, and  <Apex:pageMessages/> on the page  is working fine when I check the value first like this.
   
    

i = 0;

if (i==0){

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'works in if'));

return null;

}

return 5/i;

 


 
     But what I really want is to catch the exception and display this message instead of checking value first.
 
    

i = 0;

try{

return 5/i;

}catch(Exception ex){

ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'why not working here?'+ex));

return null;

}

 

 

 

      Seems this is not working, and I still get the standard error msg page complaining divided by 0. Did I miss anything here or this is how visualforce page error msg should work?

 

Thanks,

Dawn 

Message Edited by dawnzdy on 11-23-2009 07:40 PM
Best Answer chosen by Admin (Salesforce Developers) 
David VPDavid VP

Try this :

 

 

i = 0; try{ Double d = 5/i; return d; }catch(Exception ex){ ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'why not working here?'+ex)); return null; }

 

 

 

All Answers

David VPDavid VP

Try this :

 

 

i = 0; try{ Double d = 5/i; return d; }catch(Exception ex){ ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'why not working here?'+ex)); return null; }

 

 

 

This was selected as the best answer
dawnzdydawnzdy

Wow, amzing!

Thank you very much, it works perfectly!