PHP - Exception

An exception is an event that occurs during the execution of a program that disturbs the normal flow of its instructions.they provide a way to react to exceptional circumstances such as runtime errors in a program by transferring control to special function called handlers.when error occurs within a method.

The method creates an object and handles it off to the runtime system.the object,called an exception object,contains information about the error,including its type and the state of the program when the error occurred.

The creating an exception object and handling it to the runtime system is called throwing an exception.an exception can be thrown,tried and caught within a php code block.exceptions are handled using try block,catch block and throw statement the following syntax of exception.

Try Block

A try block of php code for execution,which must include at least one catch block.the first step in constructing an exception handler is to enclose the code that might throw an exception within a try block.

Syntax


<?php
	Try
	{
	 //code
	}
?>		
							

Catch Block

Each catch block is an exception handler and handles the type of exception indicated by its argument.the catch block contains code that is executed if and when the exception handler is invoked.when an exception is thrown,php code following the statement will not be executed and php will attempt to find the first matchinf catch block.

Syntax


<?php
	Try
	{
	 //code
	}
	Catch(ExceptionType Name)
	{
	……
	}
?>	
							

Throw Statement

All method use the throw statement to throw an exception.the throw statement requires a single argument ex.throwable object.

Syntax


<?php
	Throw ;
?>		
							

Complete Exception Example


<?php
	$num=10;
	Try
	{
		If($num?<20)
		Throw new exception(:value is less than 20”);
		echo “The entered value is correct”;
	}
	Catch(exception $ex)
	{
		echo :Erroe message:.$ex->getMessage();
	}
?>		
							
Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!