Solved

I want to test the try catch by catching an error

Posted on 2014-03-09
11
388 Views
Last Modified: 2014-03-14
<!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
Comment
Question by:rgb192
  • 4
  • 4
  • 2
  • +1
11 Comments
 
LVL 58

Assisted Solution

by:Gary
Gary earned 167 total points
ID: 39916708
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
 

Author Comment

by:rgb192
ID: 39916723
<!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
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39916835
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
 
LVL 34

Assisted Solution

by:Dan Craciun
Dan Craciun earned 83 total points
ID: 39916848
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
 

Author Comment

by:rgb192
ID: 39917932
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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 58

Assisted Solution

by:Gary
Gary earned 167 total points
ID: 39918000
You need to put the throw in the try block else it won't be captured ;o)
0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39918455
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
 

Author Comment

by:rgb192
ID: 39920833
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
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 39921446
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
 

Author Closing Comment

by:rgb192
ID: 39928441
thanks for throwing try catch

An example of how error could be caught is database connection I think.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39929073
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now