Web Design and Programming Pt 13

Help Web Design and ProgrammingIn this PHP video tutorial I’ll show you how to work with exception handling.

When an error occurs in your code this code is referred to as an exception. Meaning the code runs fine Except if the user of the code does certain things. When these Exceptions occur an error is thrown and handled by code that lies somewhere else in your code.

I specifically cover the following topics in the video:

  • How to Turn on PHP Error Reporting
  • How to Handle Exceptions
  • The Try & Catch code blocks
  • The Die() function
  • How to Create Error Logs
  • And more…

If you missed the first part of this tutorial, check it out here Web Design and Programming. All of the code follows the video and can be used in anyway you would like.

Leave questions or comments below.

All the Code from the Video

<html>
<head>
<title><?php echo “Object Oriented Programming”;?></title>
</head>

<body>

<?php

# When an error occurs with your program this error is known as an exception
# If you set up code to handle errors, these exceptions are thrown to that code
# The code you use to protect against errors catches the exception and makes everything right

# Turn error reporting on E_ALL will warn on all errors and warnings
# error_reporting (0) would shutoff error reporting
# E_STRICT will notify you if your writing non-optimized code
error_reporting (E_ALL);

class errorWrangler extends Exception
{
function errorReport()
{
$error = “Error: ” . $this->getMessage() . “<br />” . $this->getFile() . “<br />” . $this->getLine() . “<br />”;
return $error;
}
}

$num1 = 1;
$num2 = 0;

try
{
if($num2 == 0)
{
throw new errorWrangler(“Can’t divide by zero”);
}
elseif($num2 == 1)
{
throw new Exception(“Don’t divide by 1″);
}
echo “$num1 divided by $num2 is ” . $num1/$num2;
}

catch (errorWrangler $e)
{
echo $e->errorReport();
error_log($e->errorReport(), 3, “errorlog.txt”);
die(‘Something bad happened’);
}

catch (Exception $e)
{
echo $e->getMessage();
}

/*
# An error handler function 1
function error_wrangler ($num1, $num2)
{
if($num2 == 0)
{
throw new Exception(“Can’t divide by zero”);
}
return true;
}

try
{
error_wrangler($num1, $num2);
echo “$num1 divided by $num2 is ” . $num1/$num2;
}

catch(Exception $e)
{
echo “Error: ” . $e->getMessage() . “<br />” . $e->getFile() . “<br />” . $e->getLine() . “<br />”;
}
*/

?>

</body>
</html>

Leave a Reply

Your email address will not be published.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Switch to our mobile site