throwing exception and trigger_error

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
harrylynn
Forum Newbie
Posts: 6
Joined: Sat Feb 20, 2010 6:26 pm

throwing exception and trigger_error

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: throwing exception and trigger_error

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: throwing exception and trigger_error

Post by Benjamin »

Using trigger_error for data validation is not an appropriate use of the PHP programming language.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: throwing exception and trigger_error

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
User avatar
Eran
DevNet Master
Posts: 3549
Joined: Fri Jan 18, 2008 12:36 am
Location: Israel, ME

Re: throwing exception and trigger_error

Post 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.
Post Reply