try / catch

소만이·2024년 1월 22일
post-thumbnail

try catch 에러 핸들링은 완전히 이해하진 못했지만 지금까지 이해한 부분을 까먹기 전에 정리해보려고 한다.
어떻게 에러를 미리 파악하고 잡을 수 있는지 아직도 신기하지만 아직까진 미리 docs를 찾아봐서 에러가 날 부분들을 파악해 잡거나 아니면 에러가 났을 때 잡으면 된다고 생각한다.
모든 에러를 다 파악할 수 없기 때문에 try catch 구문은 축소하면 축소할 수록 좋다고 한다.
즉 뭉뚱그려서 작성하지 말라는 소리다.
또한 한 코드 안에서 여러 에러가 발생할 수 있는데 그 에러 처리하는 부분이 같다면 여러개의 try catch문을 쓸 필요가 없다고 한다.

       try:
            r = session.get(URL, headers=HEAD)  << 여기서 에러 발생 예상
            start_date = pd.to_datetime('2023-01-01').strftime('%Y-%m-%d')
            if r.status_code == 200 or r.status_code == 201:
                review_list = r.json()
                num = review_list.get('meta', {}).get('paging', {}).get('total') / review_list.get('meta', {}).get('paging',
                                                                                                                   {}).get(
                    'limit')
                if type(num) == float:
                    num += 1
                for i in range(int(num)):
                    URL = f"{review_list.get('links', {}).get('next')}"
                    if URL is None or URL == "None":
                        break
                    if URL is not None and URL != "None":
                        try:
                            r = session.get(URL, headers=HEAD) << 여기서 에러 발생 예상
                            if r.status_code == 200 or r.status_code == 201:
                                review_list = r.json()
                                for j in review_list.get('data', []):
                                    review = None
                                    created_date = pd.to_datetime(j.get('attributes', {}).get('createdDate'))
                                    change_date = created_date.strftime('%Y-%m-%d')
                                    summary_date = created_date.strftime('%y%m%d')
                       except requests.exceptions.RequestException as e:
                       print(f"RequestException: {e}")
        except requests.exceptions.RequestException as e:
            print(f"RequestException: {e}")

r = session.get(URL, headers = HEAD) 이 코드에서 에러 발생이 예상된다면
이 부분만 감싸 잡아주면 된다.

       try:
            r = session.get(URL, headers=HEAD)  << 여기서 에러 발생 예상
       except requests.exceptions.RequestException as e:
            print(f"RequestException: {e}")
            //에러처리 코드
       		
       start_date = pd.to_datetime('2023-01-01').strftime('%Y-%m-%d')
       if r.status_code == 200 or r.status_code == 201:
         review_list = r.json()
         num = review_list.get('meta', {}).get('paging', {}).get('total') / review_list.get('meta', {}).get('paging',
                                                                                                                   {}).get(
                    'limit')
           if type(num) == float:
               num += 1
                for i in range(int(num)):
                    URL = f"{review_list.get('links', {}).get('next')}"
                    if URL is None or URL == "None":
                        break
                    if URL is not None and URL != "None":
                        try:
                            r = session.get(URL, headers=HEAD) << 여기서 에러 발생 예상
                        except requests.exceptions.RequestException as e:
                       print(f"RequestException: {e}")
                       //에러처리 코드
                        if r.status_code == 200 or r.status_code == 201:
                            review_list = r.json()
                              for j in review_list.get('data', []):
                                 review = None
                                 created_date = pd.to_datetime(j.get('attributes', {}).get('createdDate'))
                                 change_date = created_date.strftime('%Y-%m-%d')
                                 summary_date = created_date.strftime('%y%m%d')
                

이렇게 try catch 구문을 축소시켜 에러 처리를 하고 다음 로직을 진행하는 것이 훨 좋다는 것을 알았다.
여기서 더 알게된 사항들이 있으면 추가를 해놔야겠다!!

0개의 댓글