?
Solved

I want to test the try catch by catching an error

Posted on 2014-03-09
11
Medium Priority
?
451 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 4
  • 2
  • +1
11 Comments
 
LVL 58

Assisted Solution

by:Gary
Gary earned 668 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 35

Assisted Solution

by:Dan Craciun
Dan Craciun earned 332 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
 
LVL 58

Assisted Solution

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

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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 111

Accepted Solution

by:
Ray Paseur earned 1000 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 111

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

801 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