PHP에서 try… catch 블록을 효율적으로 사용하는 방법
내 PHP 코드에서 try..catch 블록을 사용하고 있지만 올바르게 사용하고 있는지 확실하지 않습니다.
예를 들어, 내 코드 중 일부는 다음과 같습니다.
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
$tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (Exception $e) {
return $e;
}
따라서 트랜잭션에서 예외가 발생하면 처리 할 수 있기 때문에 동일한 try / catch 블록에서 여러 데이터베이스 작업을 그룹화합니다.
나는 그것이 다음보다 더 읽기 쉽고 효율적이라고 생각하기 때문에 그렇게하고 있습니다.
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
} catch (Exception $e) {
return $e;
}
try {
$tableBresults = $dbHandler->doSomethingWithTableB();
} catch (Exception $e) {
return $e;
}
비록 내가하는 일이 좋은 습관인지 아니면 예외를 잡는 게으른 방법인지는 잘 모르겠습니다.
내 가정은 예외에 특별한 처리가 필요한 경우에만 자체 try / catch 블록이 있어야하며 그렇지 않으면 동일한 try / catch에서 그룹화하는 것이 좋습니다.
그래서 내 질문은 다음과 같습니다.
데이터베이스 트랜잭션 당 try / catch 블록을 사용하는 이점이 있습니까? 또는 전혀 문제없이 동일한 try / catch 블록에서 여러 데이터베이스 트랜잭션을 그룹화 할 수 있습니까?
try / catch 블록을 중첩해도 괜찮습니까? 감사!
편집하다
return 문은 주로 데모 목적으로 만 사용되었지만 catch()해당 메서드에 대한 AJAX 요청을 만들고 Javascript가 JSON 개체를 예상하기 때문에 return in도 사용 하고 있습니다. 예외가 발생하면 빈 JSON 인코딩 배열을 반환합니다. . 내 예제에 특정 코드를 넣는 데 어떤 가치도 추가하지 않을 것이라고 생각했습니다.
중요 사항
다음 토론에서는 위의 예에서와 같이 구조화 된 코드에 대해 이야기하고 있다고 가정합니다. 어떤 대안을 선택하든 예외로 인해 메서드가 중간에 있던 작업을 논리적으로 중지하게됩니다.
try블록의 어떤 문 이 예외를 throw 하더라도 동일한 작업을 수행하려는 한, 단일 try/ 를 사용하는 것이 확실히 좋습니다 catch. 예를 들면 :
function createCar()
{
try {
install_engine();
install_brakes();
} catch (Exception $e) {
die("I could not create a car");
}
}
다중 try/ catch블록은 오류를 정확히 발생시킨 특정 방식으로 오류를 처리 할 수 있고 처리하려는 경우 유용합니다.
function makeCocktail()
{
try {
pour_ingredients();
stir();
} catch (Exception $e) {
die("I could not make you a cocktail");
}
try {
put_decorative_umbrella();
} catch (Exception $e) {
echo "We 're out of umbrellas, but the drink itself is fine"
}
}
후손을 위해 대답은 너무 늦을 수 있습니다. 변수의 반환 값을 확인하고 예외를 throw해야합니다. 이 경우 프로그램은 예외가 발생하는 위치에서 catch 블록으로 점프 할 것입니다. 아래서 찾다.
try{
$tableAresults = $dbHandler->doSomethingWithTableA();
if (!tableAresults)
throw new Exception('Problem with tableAresults');
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if (!tableBresults)
throw new Exception('Problem with tableBresults');
} catch (Exception $e) {
echo $e->getMessage();
}
단일 try catch 블록이 더 읽기 쉽습니다. 중요한 오류 유형을 식별하는 경우 예외를 사용자 지정하는 것이 좋습니다.
try {
$tableAresults = $dbHandler->doSomethingWithTableA();
$tableBresults = $dbHandler->doSomethingElseWithTableB();
} catch (TableAException $e){
throw $e;
} catch (Exception $e) {
throw $e;
}
There is no reason against using a single block for multiple operations, since any thrown exception will prevent the execution of further operations after the failed one. At least as long as you can conclude which operation failed from the exception caught. That is as long as it is fine if some operations are not processed.
However I'd say that returning the exception makes only limited sense. A return value of a function should be the expected result of some action, not the exception. If you need to react on the exception in the calling scope then either do not catch the exception here inside your function, but in the calling scope or re-throw the exception for later processing after having done some debug logging and the like.
When an exception is thrown, execution is immediately halted and continues at the catch{} block. This means that, if you place the database calls in the same try{} block and $tableAresults = $dbHandler->doSomethingWithTableA(); throws an exception, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will not occur. With your second option, $tableBresults = $dbHandler->doSomethingElseWithTableB(); will still occur since it is after the catch{} block, when execution has resumed.
There is no ideal option for every situation; if you want the second operation to continue regardless, then you must use two blocks. If it is acceptable (or desirable) to have the second operation not occur, then you should use only one.
in a single try catch block you can do all the thing the best practice is to catch the error in different catch block if you want them to show with their own message for particular errors.
try
{
$tableAresults = $dbHandler->doSomethingWithTableA();
if(!tableAresults)
{
throw new Exception('Problem with tableAresults');
}
$tableBresults = $dbHandler->doSomethingElseWithTableB();
if(!tableBresults)
{
throw new Exception('Problem with tableBresults');
}
} catch (Exception $e)
{
echo $e->getMessage();
}
There is no any problem to write multiple lines of execution withing a single try catch block like below
try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}
The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.
When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:
try{
install_engine();
install_break();
}
catch(Exception $e){
show_exception($e->getMessage());
}
try{
install_body();
paint_body();
install_interiour();
}
catch(Exception $e){
throw new exception('Body Makeover faield')
}
For more detail about how you can use try catch block in different cases you may refer to my blog on PHP Try Catch
참고URL : https://stackoverflow.com/questions/17549584/how-to-efficiently-use-try-catch-blocks-in-php
'program story' 카테고리의 다른 글
| 텍스트 파일에서 UTF-8이 아닌 문자를 제거하는 방법 (0) | 2020.10.19 |
|---|---|
| runtime.Gosched는 정확히 무엇을합니까? (0) | 2020.10.19 |
| Neo4J는 ID로 노드 가져 오기 (0) | 2020.10.19 |
| 창 핸들이 만들어 질 때까지 컨트롤에서 Invoke 또는 BeginInvoke를 호출 할 수 없습니다. (0) | 2020.10.19 |
| UIButton에 그림자를 추가하는 방법은 무엇입니까? (0) | 2020.10.18 |