PHP Try Catch Exception & Error Handling Tutorial

Today, We want to share with you PHP Try Catch Exception & Error Handling Tutorial.In this post we will show you wordpress plugin require another plugin, hear for Exception Handling & Error Reporting – PHP Tutorial we will give you demo and example for implement.In this post, we will learn about Using PHP try catch throw Techniques to Handle Exceptions with an example.

PHP Try Catch Exception & Error Handling Tutorial

There are the Following The simple About PHP Try Catch Exception & Error Handling Tutorial Full Information With Example and source code.

As I will cover this Post with live Working example to develop Throwing exceptions in a PHP Try Catch block, so the PHP 5 Exception Handling using try, catch and throw is used for this example is following below.

What is an Exception?

PHP – An error is an unexpected computer program result data that cannot be handled by the computer program itself.

PHP Error handling is the one type process of catching all the errors raised by your main computer program and then taking related/appropriate action.

Introduction To PHP Exception Handling,What is an Exception,Try, throw and catch,Custom Exception Class,Multiple,Re-throwing,Set a Top Level Exception Handler.

PHP Error handling

  • Die statements
  • Custom error handlers
  • PHP error reporting

Source of the native class Exception Source Code : PHP Try Catch Exception

<? php
    class Exception 
    {
    	// Message of exception
        protected $ message = 'Unknown exception'; 

        // Exception code defined by the user  
        protected $ code = 0;  

        // Source filename of exception
        protected $ file; 

        // Source line of the exception
        protected $ line; 
        function __construct (string $ message = NULL, int code = 0);

        // Message of exception
        final function getMessage (); 

        // Exception code
        final function getCode (); 

        // Source filename
        final function getFile (); 

        // Line of the source file
        final function getLine(); 

        // An array of backtrace ()
        final function getTrace (); 

        // Formatted string trace
        final function getTraceAsString (); 
        / * * Replaceable /

        // Formatted string for display
        function __toString (); 
    }
?>

PHP try, throw and catch

Error handling examples

Also Read :  Nested try catch block in PHP - Exception handling

creating a function containing a potential exception

<?php
  
  function statusNumber($num_ber) {
    if($num_ber > 1) {
      throw new Exception('The Data value has to be 1 or lower');
    }
    return true;
  }

  try {
    statusNumber(2);
    echo 'The Data value is 1 or lower';
  } catch(Exception $e) {
    echo 'Message: ' .$e->getMessage();
  }
?>

PHP Custom Exception Class

<?php
  class generalException extends Exception {
    public function error_message() {
      $error_msg = 'Error caught on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }

  $email = "[email protected]";

  try {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      throw new generalException($email);
    }
  } catch (generalException $e) {
    echo $e->error_message();
  }
?>

PHP Multiple Exceptions Handling

<?php
  class generalException extends Exception {
    public function error_message() {
      //error message
      $error_msg = 'Error caught on line '.$this->getLine().' in '.$this->getFile()
        .': <b>'.$this->getMessage().'</b> is no valid E-Mail address';
      return $error_msg;
    }
  }

  $email = "[email protected]";

  try {
    if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
      throw new generalException($email);
    }
    if(strpos($email, "example") !== FALSE) {
      throw new Exception("$email contains'example'");
    }
  }
  catch (generalException $e) {
    echo $e->error_message();
  }
  catch(Exception $e) {
    echo $e->getMessage();
  }
?>

PHP Re-Throwing Exceptions

In this example learn to :checking for “gmail” in mail address, throwing an exception if email is not valid, re-throwing exception, display custom message in PHP Try Catch Exception.

Also Read :  How to Import and Export CSV Files Using Codeigniter and MySQL

<?php
  class generalException extends Exception {
    public function error_message() {
      //error message
      $error_msg = $this->getMessage().' is no valid E-Mail/gmail address.';
      return $error_msg;
    }
  }

  $email = "[email protected]";

  try {
    try {
      if(strpos($email, "gmail") !== FALSE) {
        throw new Exception($email);
      }
    } catch(Exception $e) {
      throw new generalException($email);
    }
  } catch (generalException $e) {
    echo $e->error_message();
  }
?>

Top Level Exception Handler in PHP

<?php
  function CustomException($exception) {
    echo "<b>Your Exception is </b> " . $exception->getMessage();
  }

  set_exception_handler('CustomException');

  throw new Exception('Sorry!!, Uncaught Exception has been caught');
?>

Simple PHP Exception Handling

  1. php exception class
  2. php try catch fatal error
  3. php exception types
  4. php catch warning
  5. set_exception_handler
  6. php exception codes

Basic Usage

<?php
function check_num($number) {
  if($number>1) {
    throw new Exception("The value has to be 1 or lower");
  }
  return true;
}

check_num(3);
?>

PHP Try Catch: Basics & Advanced PHP Exception Handling Tutorial

Simple PHP try catch example

try {
    // run your simple PHP code here
}
catch (exception $e) {
    //PHP code to handle the error/exception
}
finally {
    //here optional source code that always runs
}

PHP try catch with multiple exception types

try {
    // run simple your PHP code here
}
catch (Exception $e) {
    echo $e->getMessage();
}
catch (InvalidArgumentException $e) {
    echo $e->getMessage();
}

Global PHP exception handling

function custome_global_exception_handler($exception) {
    echo "Our Exception:" . $exception->getMessage();
}

set_exception_handler(‘custome_global_exception_handler’);

PHP Exception Handling Examples:

Exception handling in PHP:

<?php 

function website($var) { 
	echo " Before try block"; 
	try { 
		echo "\n Inside try block"; 
			
		if($var == 0) 
		{ 
			
			throw new Exception('Number is zero.'); 
			echo "\n After throw (It will never be executed)"; 
		} 
	} 
		
	catch(Exception $e) { 
			echo "\n Exception Caught", $e->getMessage(); 
		} 
		
		echo "\n After catch (will be always executed)"; 
} 

website(5); 
website(0); 
?> 

normal try catch and finally block in PHP

<?php 
function website($var) { 
	
	echo " Before try block"; 
	try { 
		echo "\n Inside try block"; 
			
		if($var == 0) { 
			throw new Exception('Number is zero.'); 
			echo "\n After throw it will never be executed"; 
		} 
	} 
		
	catch(Exception $e) { 
		echo "\n Exception Caught" . $e->getMessage(); 
	} 
	finally { 
		echo "\n Here cleanup activity will be done"; 
	} 
		
	echo "\n After catch it will be always executed"; 
} 


website(5); 

website(0); 
?> 

Custom Exception Class

<?php 
class myException extends Exception { 
	function get_Message() { 
		
		// Error message 
		$errorMsg = 'Error on line '.$this->getLine(). 
					' in '.$this->getFile() 
		.$this->getMessage().' is number zero'; 
		return $errorMsg; 
	} 
} 

function website($a) { 
	try { 
		if($a == 0) { 
			throw new myException($a); 
		} 
	} 
	
	catch (myException $e) { 
		echo $e->get_Message(); 
	} 
} 

website(5); 
website(0); 
?> 

Web Programming Tutorials Example with Demo

Read :

Also Read :  Laravel Send Mailgun Mail using PHP cURL

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Try Catch Exception & Error Handling Tutorial.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Reply

avatar
  Subscribe  
Notify of