[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now

x
?
Solved

I want to test the try catch by catching an error

Posted on 2014-03-09
11
Medium Priority
?
467 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

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

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

650 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