2015. 7. 29. 09:39 IT/php
php에서 try catch finally 사용하기
try catch finally 정말 참으로 반가운 기능입니다.
try catch를 처음 접해보신분은 이런거 몰라도 된다고 생각하실지 모르시겠지만
예문을 보시고 도입해보고 싶다 라고 느끼시면 좋겠습니다.
기존 방식
$file = '/source/padudu.txt'; $result = true; if(!is_dir(dirname($file))) { if(!mkdir(dirname($file), 0777, true)) { $result = false; } } if($result) { if(!copy($file, '/target/padudu.txt')) { $result = false; } } if($result) { echo 'success!!'; } else { echo 'fail!!'; }
파일을 복사하는 부분인데 중간중간 계속해서 $result 를 찍어서 확인해야 합니다.
그런데 만약 저 중간에 이미지 처리까지 하게된다면... 대략 아득해지죠.
try catch finally 를 응용해 봅시다.
try { $file = '/source/padudu.txt'; $result = true; if(!is_dir(dirname($file))) { if(!mkdir(dirname($file), 0777, true)) { throw new Exception('mkdir ('.$file.')'); } } if(!copy($file, '/target/padudu.txt')) { throw new Exception('copy ('.$file.')'); } } catch(Exception $e) { echo 'fail:'.$e->getMessage().'('.$e->getLine().')'; } // php 5.5 이상 혹은 finally 필요시 추가 및 응용 //finally //{ // echo 'success!!'; //} // php 5.5 이하 혹은 finally 필요없을시 echo 'success!!';
보이시나요? 중간중간 $result를 안찍어봅니다.
왜냐구요? 중단해야하는 부분에 throw new Exception 찍어놓으면 마치 while 구문안의 break 처럼 동작하면서 catch로 이동되기 때문이죠!!
예문에는 에러발생 포인트가 2개밖에 없지만 실 서비스에 이용하시다보면.. 아시죠? ㅎㅎ
실 서비스를 위해 심화 예제를 만들어보았습니다.
function foo() { throw new Exception('foo function error'); } class bar { public function fun() { throw new Exception('bar class error'); } } try { foo(1); bar::fun(2); } catch(Exception $e) { echo 'fail:'.$e->getMessage().'('.$e->getLine().')'; } // php 5.5 이상 혹은 finally 필요시 추가 및 응용 //finally //{ // echo 'success!!'; //} // php 5.5 이하 혹은 finally 필요없을시 echo 'success!!';
보이시나요?
try 안에서 펑션과 클래스를 호출시 발생하는 throw new Exception도 잡습니다.
느낌이 오시나요? 기존에 자작해왔던 에러관리기능이 필요없게 된겁니다.
참고로 제한사항이 있습니다. try catch 는 php 5.1.0 버전 이상부터 지원되고 finally 는 5.5 이상부터 지원됩니다.
오늘은 비도 와서 꿀꿀한데 즐코딩하세요~!
'IT > php' 카테고리의 다른 글
php 정확한 저번달 저번주 어제 날짜 구하기 (0) | 2015.08.18 |
---|---|
php session_register 에러 (0) | 2015.07.29 |
php referer 검색어(키워드) 추출하기 (0) | 2015.07.27 |
php session redis로 설정 (0) | 2015.07.22 |