1 분 소요

예외 처리 기본구문

  • try : 에러가 발생이 예상되는 코드를 실행하는 블럭

  • except 에러명1(ValueError) : 에러를 받아서 처리해주는 블럭

  • except 에러명2(TypeError) : except 블럭은 여러개 사용 가능

  • else : try블럭에서 에러가 없이 수행될 경우 실행되는 블럭

  • finally : 반드시 실행되는 블럭

city = ['Seoul', 'Daegu', 'Daejeon']

try:
    a = 'Seoul'
#     a = 'Pusan'
    b = city.index(a)
    print(b)
except ValueError:
    print('에러 발생')
    print('참조 Value 없습니다!!!!')
else:
    print('Okay!!!')
    에러 발생
    참조 Value 없습니다!!!!

 

city = ['Seoul', 'Daegu', 'Daejeon']

try:
#     a = 'Seoul'
    a = 'Pusan'
    b = city.index(a)
    print(b)
    # 어떤 에러가 일어날지 모르는 경우 Exception
except Exception:
# except :    
    print('에러 발생')
    
else:
    print('Okay!!!')
    에러 발생

 

city = ['Seoul', 'Daegu', 'Daejeon']

try:
    a = 'Seoul'
#     a = 'Pusan'
    b = city.index(a)
    print(b)
    # 어떤 에러가 일어날지 모르는 경우 Exception
except Exception as e:
    print(e)
    
else:
    print('Okay!!!')

finally : 
    print('반드시 실행')
    0
    Okay!!!
    반드시 실행

 

city = ['Seoul', 'Daegu', 'Daejeon']

try:
#     a = 'Seoul'
    a = 'Pusan'
    b = city.index(a)
    print(b)
    # 어떤 에러가 일어날지 모르는 경우 Exception
except Exception as e:
    pass # 임시로 에러 해결할 경우의 예외 처리
    
else:
    print('Okay!!!')

finally : 
    print('반드시 실행')
    반드시 실행

 

city = ['Seoul', 'Daegu', 'Daejeon']

try:
#     a = 'Seoul'
    a = 'Pusan'
    b = city.index(a)
    print(b)
   
except ValueError:
    print('참조 Value가 잘못되었습니다.')        
except IndexError:
    print('Index 에러 입니다.')       
except Exception as e:
    print(e)  
    
else:
    print('Okay!!!')

finally : 
    print('반드시 실행')
    참조 Value가 잘못되었습니다.
    반드시 실행

 

try:
    fp = open('testttt.txt', 'r')
except:
    print('파일이 없습니다....')
finally:
    fp.close()
    파일이 없습니다....
    


    ---------------------------------------------------------------------------

    NameError                                 Traceback (most recent call last)

    ~\AppData\Local\Temp/ipykernel_8704/916169829.py in <module>
          4     print('파일이 없습니다....')
          5 finally:
    ----> 6     fp.close()
    

    NameError: name 'fp' is not defined

 

try:
    try:
        fp = open('testttt.txt', 'r')
    except:
        print('파일이 없습니다....')
    finally:
        fp.close()
except Exception as e:
    print(e)
    파일이 없습니다....
    name 'fp' is not defined

 

try:
    with open('./test.txt', 'r') as fp:
        lines = fp.readlines()
        print(lines)
except Exception as e:
    print(e)
    [Errno 2] No such file or directory: './test.txt'

 

예외 발생시키기

개발자가 직접 예외 발생(raise)


try:
#     id = 'kim'
    id = 'lee'
    if id == 'kim':
        print('OK 승인 완료')
    else:
        raise ValueError # kim이 아닌 경우에는 반드시 ValueError를 발생
except ValueError:
    print('승인 거절 !!')
except Exception as e:
    print(e)
else:
    print('Okay~~')
    승인 거절 !!

카테고리:

업데이트:

댓글남기기