logo

Exceptions in PHP

Add comment

PHP supports two ways of reporting the problem in the code. Errors and exceptions . What’s the difference then?

First at all, exceptions are object-oriented way of processing errors, while error are procedural (using functions) way of reporting the problem. Which of them is better to use? Definitely exceptions, as they offer much more control over the code. PHP has a standard class Exception, which can be extended. It contains a few basic methods (functions) and variables that can be used. Exceptions are modern way to handle problems. Functions that come with PHP are using the errors, but they can be easily translated into exceptions.

Exception class:

Exception {

	protected $message;

	private $string;

	protected $code;

	protected $file;

	protected $line;

	private $trace;

	final private function __clone() {}

	function __construct( $message = NULL, $code = 0 ) {
		if ( func_num_args () ) {
			$this -> message = $message;
		}
		$this -> code = $code;
		$this -> file = __FILE__;
		$this -> line = __LINE__;
		$this -> trace = debug_backtrace ();
		$this -> string = StringFormat ( $this );
	}

	final public function getMessage() {
		return $this -> message;
	}

	final public function getCode() {
		return $this -> code;
	}

	final public function getFile() {
		return $this -> file;
	}

	final public function getLine() {
		return $this -> line;
	}

	final public function getTrace() {
		return $this -> trace;
	}

	final public function getTraceAsString() {
	}

	public function __toString() {
		return $this -> string;
	}
}

Why then are they so useful? Because they are object-oriented code, they give you great control over the code. They can be extend, and you can have a large number of different classes that inherit a single one, but each can have a different functionality. Suppose you have in your project connecting to the database, opening and saving files and sending e-mail messages. Now, for each part  of those, you can create a class that will take care of the problems only in that part of the code. You can, for example, write code that will send e-mail message to the administrator if there are problems with connecting to the database. And now if your-mail is not sent, the second class (which takes care about problems when sending e-mail) will take the matter into his own hands and create an entry in the log file. They offer a very simple way of linking code. If you where using errors to handle problems, you would create custom function that would use if … elseif … else commands and you would, based on the types of error, choose how it should be reported. I’m not saying that this way is not good, but it is much easier to use exceptions. You’ll have less headaches when you should change the code, because you have separated classes and you have much more control over this part, without jeopardize the functionality of others. Because they are smaller classes and the extend a large class, you are ensured that when you  modify the main class, it will be applied to all smaller classes.

Now how do I use exceptions?

Exceptions include the three major commands, and they are try, catch and throw. In short, try command executes the code, that is, trying to make it until we came to the execution of throw command. This command throws the exception. When I say throw I do not mean literally, but it only creates an object that is our exceptions. In this class you can forward all that you have defined in __construct  function. Now, when it cames to throwing, all the code that was defined in a try block after throw command is skipped and PHP searches first catch command, which corresponds to our exception class name. How do you mean corresponds? It means you can define multiple catch blocks of code, but each corresponds to one exception. Exception name in catch conditions should be the same as class name that is used to create exception. That means when i say correspond. Now, when PHP has found corresponding catch block of code, he executes it and continuous with the rest of the code. If he did not found the appropriate block of code, it throws an error and stops code execution.

The basic syntax is as follows.

try {
 	/*
	Code that is executed until it comes to throwing of exceptions. If it does not comes to throwing,
	whole code block will be executed and catch block will be skipped.
	*/
}
catch  ( Exception $varijabla ) {
	/*
	This code will be executed if the thrown exception is equal to the class name in catch block (in our case, Exception).
	$variable holds instances of our Exception class.
	*/
}

Here’s an example where exception throws error when we try to divide with 0.

function divide ( $brojnik, $nazivnik ) {
	if ( $nazivnik === 0 ) {
		throw new Exception ( 'Dividing with 0 is not defined.' );
	}
	return $brojnik / $nazivnik;
}
try {
	divide ( 10, 0 );
}
catch ( Exception $e ) {
	echo $e -> getMessage ();
}

We define a function divide that receives two arguments. The first is the dividend and the second divisor. When they are forwarded to the function, it first checks whether the divisor is equal to 0 (dividing with 0 is not defined) and if this is true it throws an exception. Code after throw statement “return $brojnik / $denominator;“ will not be executed. Our function is called within the try statement, and since we forward 0 as a divisor, an exception will be thrown and catch statement will be executed. This section only lists the error, but you can make it to do anything.

That would be introduction to exceptions. If you did not understand, leave a comment and I will explain.

Related Posts
  • 27.07.2010 -- Upload Images With MySQL (0)
    [tinytoc level="1"]Intro[/tinytoc] Ok, let's continue with tutorial requests. This tutorial will ...
  • 16.07.2010 -- Packt Special Offer (1)
    Packt Publishing has new offer for this hot summer. Have a someones birthday soon and don't know ...
  • 21.05.2010 -- Multi-Language Site (6)
    It's been a while since I last posted something because I was very busy. So let's do something usefu...
  • 07.04.2010 -- Edit XML (15)
    I had an idea about creating tutorial that will cover manipulating XML in PHP. The idea was to creat...
  • 02.01.2010 -- Enable E-mail In PHP – Win (0)
    This will be a quick tutorial that will show you how to enable e-mail function in PHP on Windows....
  • 23.12.2009 -- Learning Resources (0)
    Reader Satish requested a list of tutorials where he could learn about PHP, MySQL and jQuery. Since ...
  • 25.11.2009 -- Implementing Bitwise Permissions (0)
    Reader Freddy requested a tutorial about implementing bitwise permissions in real application. This ...

logo

2 comments to “Exceptions in PHP”

  1. [...] on internet is about connection PHP with MySQL. We use exceptions to handle errors (check tutorial Exceptions in PHP for more [...]

  2. Reading fan says:

    Thanks !! very helpful post!

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2010 php4every1.com