Page 1 of 1

throwing exception and trigger_error

Posted: Mon Feb 22, 2010 11:03 am
by harrylynn
This is confusing. Can anybody tell me what is the obvious difference between throwing an exception and using trigger_error() function ? According to my knowledge, exception are used to handle runtime error and if that's the case

Code: Select all

 
if($number>1)
trigger_error("Value must be less than 1");
 
and

Code: Select all

 
try
{ 
...
if($number>1)
throw new Exception ("Value must be less than 1");
}
catch(Exception $e)
{
//display the message
}
 
aren't they serve the same purpose anyway ? Please somebody point me out what i'm missing here. Thanks all in advance.

Re: throwing exception and trigger_error

Posted: Mon Feb 22, 2010 12:13 pm
by pickle
Errors and exceptions are quite different. Errors aren't necessarily fatal, and can be routed through custom error handling functions if required. Exceptions are fatal if not handled (caught) and can be routed through custom Exception classes.

In your example, you would use trigger_error() if the user must enter a number > 1 and you want to inform them of that fact. You'd use exceptions if you were deep in a backend and a number > 1 was cause for a program exit.

Re: throwing exception and trigger_error

Posted: Mon Feb 22, 2010 9:26 pm
by Benjamin
Using trigger_error for data validation is not an appropriate use of the PHP programming language.

Re: throwing exception and trigger_error

Posted: Tue Feb 23, 2010 9:58 am
by pickle
astions wrote:Using trigger_error for data validation is not an appropriate use of the PHP programming language.
I don't see why not. The docs themselves use a similar situation in their example.

Re: throwing exception and trigger_error

Posted: Tue Feb 23, 2010 11:33 am
by Eran
I agree with astions, errors are for logging and maintenance / debugging purposes. I would not consider form validation failure to be an "error" in that sense. As an aside, I wouldn't use 80% of the code samples in the manual, as they are, in a real project.