Unit 7-PHP
Unit 7-PHP
Contents
Unit 7: Exception Handling 2
Learning Objectives 2
Introduction to Exception 3
Exception Propagation 6
Summary 11
Problems to Solve 12
Introduction to Exception
An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the
program's instructions. It can also be defined as abnormal event that arises during the execution of a program.
With PHP 5 came a new Object Oriented approach of dealing with errors. Exceptions give us much better
handling of errors and allow us to customize the behavior of our scripts when an error (Exception) is
encountered.
An exception is not an error. An exception, as the name implies, is any condition experienced by your program
that is unexpected or not handled within the normal scope of your code. Generally, an exception is not a fatal
error that should halt program execution, but a condition that can be detected and dealt with in order to continue
properly. Let us see an example of how an exception occurs and how to handle it.
echo "Todays Date<br><br>";
$dateTime = new DateTime("now", new DateTimeZone('Asia/Calcutta'));
echo $dateTime->format("d-m-y");
The above program will display the current date according to the asia/calcutta time zone, suppose if we give
some invalid timezone for example:
echo "Todays Date<br><br>";
$dateTime = new DateTime("now", new DateTimeZone('sample/Calcutta'));
echo $dateTime->format("d-m-y");
The output for the above code is:
Here we get an exception since we have given an invalid timezone. Once we get an exception it halts execution
and causes the program to abort. To avoid this problem we need to handle the exception.
When an exception occurs within a block, it creates an object and hands it off to the runtime system. The object,
called an exception object, contains information about the exception, including its type and the state of the
program when the error occurred. Creating an exception object and handing it to the runtime system is called
throwing an exception.
If an exception occurs, it is passed to the catch block. The catch block will contain a code to handle the
exception. The catch block looks like:
catch(Exceptiontype name)
{
statements;
}
Note: The catch block should come immediately after the try block. Lets try with multiple catch blocks.
The previous example can be modified as:
try
{
echo "Current Date<br><br>";
$dateTime = new DateTime("now", new DateTimeZone('sample/Calcutta'));
echo $dateTime->format("d-m-y");
}
catch(Exception $e)
{
echo "provide a valid time zone";
}
Here we get an exception, an exception object is created and it is thrown to the corresponding catch block. In
the above program we have handled the exception and the normal flow of the program does not get aborted.
$stuname="john";
$age=-23;
$mark=56;
try
{
if($age<=0)
{
throw new NegativeageException("Age can't be negative");
}
}
catch(NegativeageException $n)
{
echo $n->getInfo();
}
?>
We have created a new class, NegativeageException with a method getInfo() and a parameter constructor.
Since this class has extended the exception class all the public methods and properties for an Exception class
can be accessed inside NegativeageException class.
In the above example we have used the keyword throw. The throw is used t o throw an exception explicitly.
$stuname="john";
$age=23;
$mark=400;
try
{
if($age<=0)
{
throw new NegativeageException("Age can't be negative");
}
if($mark>100)
{
throw new Exception();
}
}
catch(NegativeageException $n)
{
echo $n->getInfo();
}
catch(Exception $e)
{
echo "The marks should range from 0 to 100";
}
In the above code, inside the try block we have checked multiple conditions. If the user gives the marks greater
than 100 it will throw an Exception and its catch block will be executed.
If the user gives a negative value or o for age it will throw NegativeageException and the corresponding catch
block will be executed. Even though we have handled the NegativeageException it will not execute the
remaining statements in try block.
Exception Propagation
When an exception occurs and if it is not caught by any of the catch block s, it looks for its handler and if it fails to
find one it just propagates from one method to the other and ends up crashing the program. For example:
function displaydate()
{
try
{
echo "Current Date<br><br>";
$dateTime = new DateTime("now", new DateTimeZone('sample/Calcutta'));
echo $dateTime->format("d-m-y");
}
catch(MyException $e)
{
}
}
try
{
In the above code when we invoke displaydate() function it will generate an exception because of he invalid
timezone. Since there is no corresponding catch block in the displaydate() function, it propagates it to the calling
part. In the calling part the corresponding catch block will be executed. When we get exceptions either we can
handle them inside the function or we can propagate them to the calling part.
In the above example we have opened a file employeedetails.dat for reading. If the file exists it will return a file
pointer else it will return 0. We should get the output as either reading or file does not exist, but the output here
is;
Since the file employeedetails.dat does not exist the fopen function returns zero and we get the message File
does not exist as output, but along with the message we also get a warning. To avoid this warning in our script
we can set the error-reporting level as error-reporting (E_ USER_ERROR). We can modify the above program
as:
error-reporting(E_ USER_ERROR);
$fp=fopen("employeedetails.dat","r");
if($fp)
{
echo "Reading";
}
else
{
echo "File does not exist";
}
With this code in place, all errors that are enabled by the error-reporting level will direct through our custom
function, with the unfortunate exception of a fatal error.
For Example:
<?php
include(LoanDetails.html>
?>
In the above code we have included the LoanDetails.html. If the file does not exist we will get a warning as the
output;
Now instead of showing the warning to the end user, we can set the custom error handler to display a custom
message as:
<?php
function error_handler($errno, $errmessage)
{
}
set_error_handler(error_handler);
include(LoanDetails.html);
?>
For the above code if the file does not exist we will get a message Sorry for the inconvenience, Please try again
later!!!!!!!
Summary
Now that you have completed this unit, you should be able to:
Know what an exception is and how to handle it.
Know PHPs built-in error reporting levels, and how to handle errors with custom error handlers and
exception handling.
Problems to Solve
1. Create a Class Employee with id, name, age, gender, designation and salary. Write a function
displayEmployeeDetails() to accept an Employee Object and display the details of the employee.
Designation of the employee can be either programmer, Project lead or Team Member. The function
should throw a DesignationImproperException (with a meaningful message) if the designation of an
employee is not any of these.
2. Write a function called viewEmployeeDetails (), which calls the displayEmployeeDetails() method in
Question 1. Modify the displayEmployeeDetails () function to propagate the DesignationImproperException
that is handled in viewEmployeeDetails() function that displays a message called Sorry!!!! Employee Details
Cannot be Viewed.
3. Write a program to read the student details from the student.dat file. If the student.dat file does not exist
define your own error handler to handle the error.