You are on page 1of 12

Course Handout Student Notebook

Contents
Unit 7: Exception Handling 2

Learning Objectives 2

Introduction to Exception 3

Exception Handling Mechanism 4

Creating Custom Exceptions 5

Multiple Catch Blocks 5

Exception Propagation 6

Error Handling in PHP 7

Summary 11

Problems to Solve 12

Copyright IBM Corp. 2011 Course Contents 1


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
PHP Core Student Notebook

Unit 7: Exception Handling


Learning Objectives
At the end of this unit, you will be able to:

Create a custom exception


Know various ways to handle an exception
Know PHPs built-in error reporting levels, and how to handle errors with custom error handlers and
exception handling.

Copyright IBM Corp. 2011 Unit 6 PHP Basics 2


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

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:

3 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

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.

Exception Handling Mechanism


Exceptions are caught and handled using a try/catch control cons truct. The first step in constructing an
exception handler is to enclose the code that might throw an exception within a try block. In general, a try block
looks like the following:
try
{
statements;
}

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.

Note: Exception is a built-in class in PHP.

Copyright IBM Corp. 2011 Unit 6 PHP Basics 4


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Creating Custom Exceptions


You can create own customized exception as per requirements of the application. PHP allows you to define your
own exception class by extending the Exception class. For example:
<?php
class NegativeageException extends Exception
{
private $info;

public function __construct($message)


{
$this->info=$message;
}
public function getInfo()
{
return $this->info;
}
}

$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.

Multiple Catch Blocks


Example with multiple catch blocks;

$stuname="john";
$age=23;

5 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

$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
{

Copyright IBM Corp. 2011 Unit 6 PHP Basics 6


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

echo "Today's date"."<br>";


echo displaydate();
}
catch(Exception $n)
{
echo "provide a valid time zone";
}

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.

Error Handling in PHP


Errors are the most common event a developer faces when programming. To reduce the number of e rrors in
your code, proper error handling is essential in your web application. PHP generates three types of errors,
depending on severity:
Notice: These errors are not serious and do not create a serious problem. Notices are PHPs way to tell
you that the code it runs may be doing something unintentional, such as reading that undefined variable.
Warning: Failed code has created an error, but does not terminate execution. Typical examples are
missing function parameters, when you include a file that does not exists.
Fatal error: A serious error condition has rendered the script unable to run. A fatal error terminates the
script. Examples are out-of-memory errors, uncaught exceptions, or class redeclaration.
Each type of error is also represented by a constant that can be referred to within your code as
E_USER_NOTICE, E_USER_WARNING, and E_USER_ERROR. The error-reporting level can be manually
defined within a script using the error-reporting() function.
To display all types of error including notices;
error-reporting(E_ALL);
To display only fatal errors;
error-reporting(E_ USER_ERROR);
Example of how to use error-reporting level in scripts;
$fp=fopen("employeedetails.dat","r");
if($fp)
{
echo "Reading";
}
else
{
echo "File does not exist";

7 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

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";
}

Copyright IBM Corp. 2011 Unit 6 PHP Basics 8


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Defining an error handler


We can write our own function to handle any error. This option gives the programmer full control over what
actions to take when an error is raised or what information should be displayed to the user when an error occurs.
By creating a function that designs a custom error message and then setting that function as the default error
handler, you can avoid the awkward and unprofessional display of errors to a user.
Creating a custom error handler is quite simple. We simply create a special function that can be called when an
error occurs in PHP. This function must be able to handle a minimum of two parameters (error level and error
message). For Example:

function error_handler($errno, $errmessage)


{
echo "Sorry for the inconvenience, Please try again
later!!!!!!!!";
}
Now that we have defined our custom error handler, we simply need to refer to the function within the code using
the set_error_handler() function as:
set_error_handler(error_handler);

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;

9 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

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)
{

echo "Sorry for the inconvenience, Please try again


later!!!!!!!!";

}
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!!!!!!!

Copyright IBM Corp. 2011 Unit 6 PHP Basics 10


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.
Student Notebook PHP Core

Summary
Now that you have completed this unit, you should be able to:
Know what an exception is and how to handle it.

Write a custom exception as per requirements of the application.

Know PHPs built-in error reporting levels, and how to handle errors with custom error handlers and
exception handling.

11 PHP Copyright IBM Corp.2011


PHP Core Student Notebook

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.

Copyright IBM Corp. 2011 Unit 6 PHP Basics 12


Course Materials may not be reproduced in w hole or in part
w ithout the prior permission of IBM.

You might also like