본문으로 바로가기

try, except 와 if else 를 써야할 때

category 장고/MTV 2019. 3. 14. 18:17

try, except 문과 if, else 문을 사용할 때는 확실히 구분짓고 써야할 것 같다. 물론 아직은 초급을 벗어나지 못한 상태이지만 상황에 따라 적절하게 써야 한다는 것에 대한 힌트는 얻게된 것 같다.


해당 뷰는 모두 댓글 삭제 기능으로 try/except 문 같은 경우에 구현하다가 예외 처리에 대한 어려움에 결국 if/else 문이 낫다고 판단하여 처리한 내용입니다.



try / except 문

- try 에서 정상적으로 작동하지만 except 문에서 에러가 발생되기 때문에 해당 코드는 실제 서비스에서는 사용할 수 없다.

- except 에 redirect 로 try 문과 동일한 경로를 지정해도 리턴하는 객체가 없다면서 ValueError 이 발생

def comment_delete(request, comment_id, product_pk):
    product = Product.objects.get(pk=product_pk)
    comment = Comment.objects.get(pk=comment_id)
    try:
        if comment.user.pk == request.user.pk:
            comment.delete()
            return redirect('productions:product-detail', product.pk)
    except Comment.DoesNotExist:
        return HttpResponse('매칭되는 댓글이 없습니다.!!')



if / else 문

- 조건문에 성립하지 않아도 아무런 동작없이 redirect 처리가 가능하다. 에러를 발생시킬 코드가 없을 경우에는 if / else 문이 적합하다.

def comment_delete(request, comment_id, product_id):
    product = Product.objects.get(pk=product_id)
    comment = Comment.objects.get(pk=comment_id)

    if comment.user.pk == request.user.pk:
        comment.delete()
        return redirect('productions:product-detail', product.pk)
    else:
        return redirect('productions:product-detail', product.pk)


실제 코드에서는 동일한 경로로 reidrect() 되기 때문에 아래와 같이 코드를 작성

def comment_delete(request, comment_id, product_id):
    product = Product.objects.get(pk=product_id)
    comment = Comment.objects.get(pk=comment_id)

    if comment.user.pk == request.user.pk:
        comment.delete()
    return redirect('productions:product-detail', product.pk)


결론은 예외처리로 에러나 message.info() 와 같은 함수를 사용할 것이 아니라면 if/else 문으로 간결하게 처리하는 것이 더 좋다.


'장고 > MTV' 카테고리의 다른 글

Login 기능 구현하기  (0) 2019.04.21
User 모델에서 Username 을 Email 로 재정의  (0) 2019.04.18
AbstractBaseUser 모델  (0) 2019.03.01
구문 분석 오류(could not parse ...)  (1) 2019.02.20
redirect 기능  (0) 2019.02.19