All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

PHP Exceptions And Errors

Exceptions and Errors are the things errors that occur in the execution of your code and stop the working.


Exception Handling you can handle any exception easily with PHP try, throw and catch function.


Error Handling you can handle any error easily with PHP die() function.You can also define you own error handling function.



Exception Handling

  • Try: A function using an exception should be in a "try" block. If the exception does not trigger, the code will continue as normal. However if the exception triggers, an exception is "thrown".

  • Throw: This is how you trigger an exception. Each "throw" must have at least one "catch".

  • Catch: A "catch" block retrieves an exception and creates an object containing the exception information.

<?php
try
{
    $error1 = 'This is the Example of Exception Handling';
    throw new Exception($error1);

    echo 'Never executed'; //This code is not executed because 
                                          before this an exception was thrown.

}
catch (Exception $e) 
{
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

// Continue execution
echo 'Hello PHP';
?>

There are following functions which can also use with exceptions

  • getMessage(): message of exception

  • getCode(): code of exception

  • getFile(): source filename

  • getLine(): source line

  • getTrace(): n array of the backtrace()

  • getTraceAsString(): formated string of trace



Error Handling

<?php

$file=fopen("example.txt","r");

/*When there is a problem in opening the file an error occurs 
that shows the full decription of the error like*/

Warning: fopen(example.txt) [function.fopen]: failed to open 
stream:No such file or directory in C:\php\demo.php on 
line 2


/*If you dont want to display that default warning you can also 
give your text to show when there is some error like that*/

if(!file_exists("example.txt"))
{
  die("No File Exist");
} 

else
{
  $file=fopen("example.txt","r");
}


/*This wiil display No File Exist if any problem occur in opening the
example.txt file*/

?>


❮ PrevNext ❯