फ़ंक्शन set_exception_handler
फ़ंक्शन set_exception_handler एक ऐसे फ़ंक्शन को परिभाषित करने की अनुमति देता है जो पकड़े नहीं गए अपवादों को संभालने के लिए कॉल किया जाएगा। पैरामीटर के रूप में हैंडलर फ़ंक्शन का नाम या एक अनाम फ़ंक्शन पास किया जाता है। हैंडलर को एक पैरामीटर के रूप में अपवाद ऑब्जेक्ट प्राप्त होता है।
वाक्य - विन्यास
set_exception_handler(callable $exception_handler): callable
उदाहरण
आइए एक साधारण अपवाद हैंडलर सेट करें:
<?php
function myExceptionHandler($exception) {
echo 'Caught exception: ' . $exception->getMessage();
}
set_exception_handler('myExceptionHandler');
throw new Exception('Something went wrong!');
?>
कोड निष्पादन का परिणाम:
'Caught exception: Something went wrong!'
उदाहरण
हैंडलर के रूप में एक अनाम फ़ंक्शन का उपयोग:
<?php
set_exception_handler(function($exception) {
echo 'Error: ' . $exception->getMessage();
});
throw new Exception('Critical error');
?>
कोड निष्पादन का परिणाम:
'Error: Critical error'
उदाहरण
पिछले हैंडलर को पुनर्स्थापित करना:
<?php
function firstHandler($exception) {
echo 'First handler: ' . $exception->getMessage();
}
function secondHandler($exception) {
echo 'Second handler: ' . $exception->getMessage();
}
set_exception_handler('firstHandler');
$old_handler = set_exception_handler('secondHandler');
restore_exception_handler(); // firstHandler को पुनर्स्थापित करता है
throw new Exception('Test');
?>
कोड निष्पादन का परिणाम:
'First handler: Test'