Here we are trying to find out how to add php try catch exception handling code in your PHP .we know that like every programming language php also as its on error handling method, Exception handling in PHP ,new object oriented way of dealing with errors, we have have PHP try catch exception handling code
Here is the syntax
//trigger exception in a "try" block
try {
}
//catch exception
catch(Exception $e) {
echo 'Error: ' .$e->getMessage();
}
See PHP try catch exception handling code with example
try {
$status = 1;
$cont = $this->conn;
$sql = "INSERTED INTO menu(display_name, menu_link, status,sort_order,menu_slug) VALUES(:menu_title,:menu_link,:status,:sort_order,:menu_slug)";
$new_db = $cont->prepare($sql);
$new_db->bindParam(':menu_title', $data['menu_title']);
$new_db->bindParam(':menu_link', $data['menu_link']);
$new_db->bindParam(':sort_order', $data['sort_order']);
$new_db->bindParam(':status', $status);
if($data['menu_slug']!='')
{
$slug_value=$data['menu_slug'];
}
else
{
$slug_value=$data['menu_title'];
}
$slug = $this->generate_sub_menu_slug($extra_string='',$slug_value);
$new_db->bindParam(':menu_slug', $slug);
$new_db->execute();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
In the above example MySQL INSERT syntax is wrong so this php code through an Exception error that says SQL state error
try {
$status = 1;
$cont = $this->conn;
$sql = "INSERT INTO menu(display_name, menu_link, status,sort_order,menu_slug) VALUES(:menu_title,:menu_link,:status,:sort_order,:menu_slug)";
$new_db = $cont->prepare($sql);
$new_db->bindParam(':menu_title', $data['menu_title']);
$new_db->bindParam(':menu_link', $data['menu_link']);
$new_db->bindParam(':sort_order', $data['sort_order']);
$new_db->bindParam(':status', $status);
if($data['menu_slug']!='')
{
$slug_value=$data['menu_slug'];
}
else
{
$slug_value=$data['menu_title'];
}
$slug = $this->generate_sub_menu_slug($extra_string='',$slug_value);
$new_db->bindParam(':menu_slug', $slug);
$new_db->execute();
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}