B.Tech Students: Apply for Live Programming Internship C, C++, Java, Python ,Web page Designing, PHP PHP Exception Handling Explained | LiveCodeProgramming

PHP Exception Handling

PHP exceptions are used to handle errors gracefully. You can use try, catch, finally, throw, and even create custom exceptions.

Basic Example:

<?php
try {
  throw new Exception("Something went wrong!");
} catch (Exception $e) {
  echo "Caught exception: " . $e->getMessage();
} finally {
  echo " - Always executed.";
}
?>

Custom Exception Example:

<?php
class MyException extends Exception {}

function checkNumber($number) {
  if ($number > 100) {
    throw new MyException("Number must not be greater than 100");
  }
  return true;
}

try {
  checkNumber(150);
} catch (MyException $e) {
  echo "Custom Error: " . $e->getMessage();
} finally {
  echo " - Done";
}
?>

Output:

Custom Error: Number must not be greater than 100 - Done

PHP में Exceptions का उपयोग errors को अच्छे से handle करने के लिए किया जाता है। आप try, catch, finally, throw और custom exceptions का प्रयोग कर सकते हैं।

बेसिक उदाहरण:

<?php
try {
  throw new Exception("कुछ गलत हो गया!");
} catch (Exception $e) {
  echo "पकड़ा गया error: " . $e->getMessage();
} finally {
  echo " - हमेशा चलेगा।";
}
?>

कस्टम Exception:

<?php
class MyException extends Exception {}

function checkNumber($number) {
  if ($number > 100) {
    throw new MyException("संख्या 100 से अधिक नहीं होनी चाहिए");
  }
  return true;
}

try {
  checkNumber(150);
} catch (MyException $e) {
  echo "कस्टम Error: " . $e->getMessage();
} finally {
  echo " - समाप्त";
}
?>

Output:

कस्टम Error: संख्या 100 से अधिक नहीं होनी चाहिए - समाप्त