在函数和主脚本中尝试捕获?
try-catch in function and in main script?
我希望得到一些有关引发异常和捕获异常的最佳实践的建议。我正在使用第 3 方库连接到 Amazon mws API。这个库已经抛出了我在函数中捕获的异常。
我的问题是,这个函数是否应该使用 try-catch 将异常传递给主脚本?例如
function myFunction() {
try {
$obj = new Object();
$obj->makeCall();
return $obj->getData();
} catch (Exception $ex) {
throw new Exception('There was a problem with the library '.$ex->getMessage());
}
}
然后在主脚本中;
try {
//make the call
$response = myFunction();
} catch (Exception $e){
//log error
$logger->error("log error");
}
如果您在主脚本中捕获异常,则不需要在您的函数中捕获它 myFunction
直到您需要在您的函数中进行一些处理。
如果它的子项或子项的子项等抛出异常,控件将return在主脚本中捕获异常。
我希望得到一些有关引发异常和捕获异常的最佳实践的建议。我正在使用第 3 方库连接到 Amazon mws API。这个库已经抛出了我在函数中捕获的异常。
我的问题是,这个函数是否应该使用 try-catch 将异常传递给主脚本?例如
function myFunction() {
try {
$obj = new Object();
$obj->makeCall();
return $obj->getData();
} catch (Exception $ex) {
throw new Exception('There was a problem with the library '.$ex->getMessage());
}
}
然后在主脚本中;
try {
//make the call
$response = myFunction();
} catch (Exception $e){
//log error
$logger->error("log error");
}
如果您在主脚本中捕获异常,则不需要在您的函数中捕获它 myFunction
直到您需要在您的函数中进行一些处理。
如果它的子项或子项的子项等抛出异常,控件将return在主脚本中捕获异常。