• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 499
  • Last Modified:

I want to test the try catch by catching an error

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Using SplFileObject</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php # Script 8.8 - write_to_file3.php
// This page uses the SplFileObject class.

// Start the try...catch block:
try {
    
    // Create the object:
    $fp = new SplFileObject('data.txt', 'w');
    
    // Write the data:
    $fp->fwrite("This is a line of data1.\n");
    
    // Delete the object:
    unset($fp);

    // If we got this far, everything worked!
    echo '<p>The data has been written.</p>';

} catch (Exception $e) {
    echo '<p>The process could not be completed because the script: ' . $e->getMessage() . '</p>';
}

echo '<p>This is the end of the script.</p>';

?>
</body>
</html>

Open in new window



using wamp, how can I create an error naturally without adding an error creation line such as
error_log("You messed up!", 3, "my-errors.log");
trigger_error('Test Error', E_USER_ERROR);
0
rgb192
Asked:
rgb192
  • 4
  • 4
  • 2
  • +1
6 Solutions
 
GaryCommented:
I don't see how you could change your code to create an exception except for manually throwing an exception
throw new Exception('Opps');
0
 
rgb192Author Commented:
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Using SplFileObject</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<?php # Script 8.8 - write_to_file3.php
// This page uses the SplFileObject class.
throw new Exception('Opps');
// Start the try...catch block:
try {
    
    // Create the object:
    $fp = new SplFileObject('data.txt', 'w');
    
    // Write the data:
    $fp->fwrite("This is a line of data1.\n");
    
    // Delete the object:
    unset($fp);

    // If we got this far, everything worked!
    echo '<p>The data has been written.</p>';

} catch (Exception $e) {
    echo '<p>The process could not be completed because the script: ' . $e->getMessage() . '</p>';
}

echo '<p>This is the end of the script.</p>';

?>
</body>
</html>

Open in new window



I added
throw new Exception('Opps'); to line 11

instead of
  echo '<p>The process could not be completed because the script: ' . $e->getMessage() . '</p>';

Fatal error: Uncaught exception 'Exception' with message 'Opps' in C:\wamp\www\phpvqp3_scripts\ch08\write_to_file3.php:11 Stack trace: #0 {main} thrown in C:\wamp\www\phpvqp3_scripts\ch08\write_to_file3.php on line 11



I want to run line 22 in the
catch (Exception $e) {}
0
 
Ray PaseurCommented:
Here is an example that shows how try / throw / catch works.  Enjoy experimenting with this.  Please read the man page references very carefully.  The Exception model in OOP is not at all intuitive and can lead to a great deal of confusion.  I would advise you to use it sparingly, if at all.  It's one of those things like multiple inheritance.  I tell my students, "Just don't do that."

<?php // RAY_try_throw_catch.php
error_reporting(E_ALL);
echo "<pre>";

// DEMONSTRATE A TRY WITH MULTIPLE CATCH BLOCKS
// EXAMPLE: RAY_try_throw_catch.php?q=1
// http://php.net/manual/en/reserved.exceptions.php
// http://php.net/manual/en/language.exceptions.php
// http://php.net/manual/en/language.exceptions.extending.php

Class ScrewUP
{
    // CONSTRUCTOR SETS A CODE PROPERTY FOR THE OBJECT
    public function __construct($q)
    {
        // CHOOSE AN INTEGER VALUE FROM ZERO TO THREE
        $this->code = 0;
        if (!empty($q)) $this->code = floor($q % 4);
    }

    // THIS WILL THROW SOME KIND OF EXCEPTION BASED ON THE CODE
    public function hiccup()
    {
        // THESE EXCEPTIONS WILL BE CAUGHT
        if ($this->code == 0) throw new Exception_zero('Hello');
        if ($this->code == 1) throw new Exception_one('World');

        // THIS WILL BE AN UNCAUGHT EXCEPTION: FATAL ERROR
        if ($this->code == 2) throw new Exception_two('Foobar');

        // THIS WILL BE AN UNEXTENDED EXCEPTION
        throw new Exception('Naked');
    }
}

Class Exception_Zero extends Exception
{
    public function __construct($x)
    {
        parent::__construct();
        echo "Exception Zero: $x ";
    }
}

Class Exception_One extends Exception
{
    public function __construct($x)
    {
        parent::__construct();
        echo "Exception One: $x ";
    }
}

// INSTANTIATE THE CLASS USING THE URL q= VARIABLE
$x = new Screwup($_GET['q']);

// RUN THE TRY/CATCH LOGIC TO THROW AN EXCEPTION
try
{
    $x->hiccup();
}
catch (exception_One $e)
{
    echo "I Have Caught Exception Number: $x->code ";
    var_dump($e);
}
catch (exception_Zero $e)
{
    echo "I Have Caught Exception Number Zero ";
    var_dump($e);
}
catch (exception $e)
{
    echo "I Have Caught an UnExtended Exception ";
    var_dump($e);
}

Open in new window

0
The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

 
Dan CraciunIT ConsultantCommented:
On your original example, simply create a data.txt file and make it read-only.
This will make this fail: $fp = new SplFileObject('data.txt', 'w');

HTH,
Dan
0
 
rgb192Author Commented:
On your original example, simply create a data.txt file and make it read-only.
This will make this fail: $fp = new SplFileObject('data.txt', 'w');

when data.txt is 000 exception is still not caught



Rays example caught an exception
Exception Zero: Hello I Have Caught Exception Number Zero object(Exception_Zero)#2

but I think that example was made to intentionally catch. Not catch in a result of an error.




I am doing tutorials writing try/catch
catch in a result of an error but I do not know of an example of an error

It would seem to me that data.txt permissions would be an error.  Should I try on another server.
0
 
GaryCommented:
You need to put the throw in the try block else it won't be captured ;o)
0
 
Ray PaseurCommented:
You may misunderstand the concept of throwing an exception.  It's similar to triggering an error, but the PHP engine will recognize exception types and will direct your program to the appropriate exception handler.  You can write throw explicitly, as I have done in the demonstration script.  Or you can wait until something fails, and if you're lucky the failure will not trigger an error, but will instead throw an exception.  In either case, if you've written the catch block(s) correctly, the exception object will be passed to your handler.

Your try block can throw many different exceptions, depending on the program logic.  Once your exception handler has finished, the script goes right on running as if nothing was amiss.
0
 
rgb192Author Commented:
You need to put the throw in the try block else it won't be captured ;o)

Or you can wait until something fails, and if you're lucky the failure will not trigger an error, but will instead throw an exception.  In either case, if you've written the catch block(s) correctly, the exception object will be passed to your handler.


I do not understand try catch Originally I thought
try{
}catch{}
was
success{
}if error{}

but there is no way to call
if error{}

so now there is a way to give a 'fake error' which will never occur
0
 
Ray PaseurCommented:
There would be no point to something that will never occur (error or not).  This is pidgin code, but maybe it will help clarify.

try{
  /* SOMETHING IN HERE _MIGHT_ THROW AN 'XYZ' EXCEPTION */
  /* OR IT MIGHT NOT - IT MIGHT JUST SUCCEED */
}
catch (XYZ Exception $exc){
  /* IF AN XYZ EXCEPTION WAS THROWN, RUN THIS CODE */
}
/* IF NO EXCEPTION WAS THROWN, THE SCRIPT COMES HERE */
/* IF THE XYZ EXCEPTION WAS THROWN, AFTER THE CATCH BLOCK RUNS, SCRIPT COMES HERE */
0
 
rgb192Author Commented:
thanks for throwing try catch

An example of how error could be caught is database connection I think.
0
 
Ray PaseurCommented:
Yes, a data base connection error would be something that could be caught.  This article shows how a PDO connection can be wrapped in a try / catch block.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now