Page 1 of 1

Php try / catch

Posted: Sat Nov 21, 2009 8:08 am
by SimonBoris
Hi everybody, i am new to this forum and hope that it will help with my learning of Php.

I have created my first try/catch block like the following.

Code: Select all

    function test(){
        try{
            
            $value = $r ; // The variable $r do not exist.
            
        }catch( Exception $error ){
            echo "Catch block" ;
        }
    }
Well, it generates an error, but it never enter the catch block. In other programming language, if an error occur in a try block, you automatically go to the catch block, but in php i need to do some validation and throw an exception.

Is this suppose to work like this or am i doing something wrong.

I am currently testing on Wamp, with Php 5.3.0

If someone have clue, please share.

Thank you.

Re: Php try / catch

Posted: Sat Nov 21, 2009 8:24 am
by iankent
$value = $r won't throw an exception. Try this line to test it:

Code: Select all

throw new Exception('this is a test exception');
and see if that works.

Re: Php try / catch

Posted: Sat Nov 21, 2009 8:50 am
by SimonBoris
HI iankent, it works when i throw an exception.

But by definition, a try/catch block, if something fail, the xeecution should stop and go immeditly in the catch block.
If i need to manually validate my code and throw an exception, try/catch are useless.

I have found that if i wish to make try/catch block work properly, i need to add the following pice of code:

Code: Select all

error_reporting(0);
Why the hell php needs this code in order for its try/catch blocks to work?

Thx

Re: Php try / catch

Posted: Sat Nov 21, 2009 8:55 am
by iankent
quote here from php manual:
Note: Internal PHP functions mainly use Error reporting, only modern Object oriented extensions use exceptions. However, errors can be simply translated to exceptions with ErrorException.
Basically, a Notice, Warning or Error isn't an Exception. An exception must be explicitly created somewhere, whether thats inside an object your using or you create it yourself with "new Exception('message')".

If you want to treat Notice, Warning and Error as Exceptions you'll need to set a default error handler and convert the exceptions to an ErrorException object and throw that yourself.

hth

edit:
presumably error_reporting(0); changes this behaviour so that they are automatically treated as exceptions

Re: Php try / catch

Posted: Sat Nov 21, 2009 9:04 am
by SimonBoris
Thank you for your help iankent.