코드 냄새 132 - 예외 범위가 너무 넓음

예외는 편리합니다. 단, 최대한 좁게

TL;DR: Be as specific as possible when handling errors.



문제


  • Fail Fast 원칙 위반
  • 누락된 오류
  • 위음성

  • 솔루션


  • 예외 처리기 범위를 최대한 좁히십시오
  • .

    샘플 코드



    잘못된




    import calendar, datetime
    try: 
        birthYear= input('Birth year:')
        birthMonth= input('Birth month:')
        birthDay= input('Birth day:')
        #we don't expect the above to fail
        print(datetime.date(int(birthYear), int(birthMonth), int(birthDay)))
    except ValueError as e:
        if str(e) == 'month must be in 1..12': 
            print('Month ' + str(birthMonth) + ' is out of range. The month must be a number in 1...12')
        elif str(e) == 'year {0} is out of range'.format(birthYear): 
            print('Year ' + str(birthMonth) + ' is out of range. The year must be a number in ' + str(datetime.MINYEAR) + '...' + str(datetime.MAXYEAR))
        elif str(e) == 'day is out of range for month': 
            print('Day ' + str(birthDay) + ' is out of range. The day must be a number in 1...' + str(calendar.monthrange(birthYear, birthMonth)))
    
    

    오른쪽



    import calendar, datetime
    
    birthYear= input('Birth year:')
    birthMonth= input('Birth month:')
    birthDay= input('Birth day:')
    # try scope should be narrow
    try: 
        print(datetime.date(int(birthYear), int(birthMonth), int(birthDay)))
    except ValueError as e:
        if str(e) == 'month must be in 1..12': 
            print('Month ' + str(birthMonth) + ' is out of range. The month must be a number in 1...12')
        elif str(e) == 'year {0} is out of range'.format(birthYear): 
            print('Year ' + str(birthMonth) + ' is out of range. The year must be a number in ' + str(datetime.MINYEAR) + '...' + str(datetime.MAXYEAR))
        elif str(e) == 'day is out of range for month': 
            print('Day ' + str(birthDay) + ' is out of range. The day must be a number in 1...' + str(calendar.monthrange(birthYear, birthMonth)))
    

    발각



    [X] 수동

    충분한 테스트 스위트가 있으면 돌연변이 테스트를 수행하여 예외 범위를 최대한 좁힐 수 있습니다.

    태그


  • 예외

  • 결론



    우리는 가능한 한 외과적으로 예외를 만들어야 합니다.

    처지







    학점



    Unsplash에서 Jakob Braun의 광자


    The primary duty of an exception handler is to get the error out of the lap of the programmer and into the surprised face of the user.



    베리티 스토브






    이 기사는 CodeSmell 시리즈의 일부입니다.


    좋은 웹페이지 즐겨찾기