• 회원가입
  • 로그인
  • 구글아이디로 로그인

[keyword] Python - except 키워드 - try...except 구문에서 에러 처리. (= 익세프트)

1398  

except 예제

 

try:

  x > 3 # 에러 유발 (∵ x 정의 안 된 상태.)

except:

  print("뭔가 오류 발생.")

print("에러 떠도, 프로그램은 계속 작동.")

 

결과값:

뭔가 오류 발생.

에러 발생해도, 프로그램은 계속 작동.

 

except 정의

 

try...except...구문에서 try 구문에 에러 있을 시, 에러 제어.

※ 여러 except 구문 사용해, 에러 종류별로 각각 제어 가능.

else 구문 사용해, 에러 없는 경우 실행할 코드 정의 가능.

finally 구문 사용해, 에러 유무와 상관없이 코드 실행 가능.

 

 

except 예제 

1. 에러 종류별 에러 처리 코드 정의 가능.

 

x = "Homzzang.com"

try:

  x > 3 # 에러 유발. (∵ 문자열과 숫자는 비교 불가.)

except NameError:

  print("정의 안 된 변수 사용")

except TypeError:

  print("다른 데이터타입의 값 비교.")

 


2. 기타 에러 정의.

 

try:

  x = 1/0 # ZeroDivisionError 에러 유발.

except NameError:

  print("정의 안 된 변수 사용.")

except TypeError:

  print("다른 데이터타입 값 비교")

except:

  print("그외 에러 발생.")

 

결과값: 그외 에러 발생.


3. Try 구문에 에러 없는 경우 출력 메세지 정의

 

x = 1

try:

  x > 2

except NameError:

  print("정의 안 된 변수 사용")

except TypeError:

  print("다른 데이터타입 값 비교.")

else:

  print("'Try' 코드가 에러 유발 없이 실행됨.") 

 

결과값: 'Try' 코드가 에러 유발 없이 실행됨.



분류 제목
dictionary Python - dictionary.get() 메서드 ★ - Dictionary에서 지정 key의 값 반환.…
dictionary Python - dictionary.items() 메서드 - Dictionary의 view 객체 반환. (=…
dictionary Python - dictionary.keys() 메서드 ★ - Dictionary의 Key List 반환. …
dictionary Python - dictionary.pop() 메서드 - Dictionary의 item 제거. (= pop메…
dictionary Python - dictionary.popitem() 메서드 - Dictionary 마지막 item 제거. …
dictionary Python - dictionary.setdefault() 메서드 ★ - 지정 key의 value 반환. (…
dictionary Python - dictionary.update() 메서드 ★ - Dictionary에 item 추가 (= …
dictionary Python - dictionary.values() 메서드 ★ - Dictionary의 Value List …
tuple Python - Tuple Method (투플 메서드) 종류
tuple Python - tuple.count() 메서드 - Tuple에서 지정요소의 개수 (= 포함횟수=중복횟수) …
tuple Python - tuple.index() 메서드 - Tuple에서 지정요소의 위치 반환. (= index메서…
set Python - Set Method (셋 메서드) 종류
set Python - set.add() 메서드 - 요소 추가 (= add메서드 = 셋애드메서드)
set Python - set.clear() 메서드 - 모든 요소 제거 (= clear메서드 = 셋클리어메서드)
set Python - set.copy() 메서드 - Set 복사 (= copy메서드 = 셋카피메서드)
set Python - set.difference() 메서드 ★ - 차집합 (= 두 set간 차이 반환 = diff…
set Python - set.difference_update() 메서드 - 두 Set의 공통요소 제거. (= di…
set Python - set.discard() 메서드 ★ - Set에서 지정요소 제거. (= discard메서드 …
set Python - set.intersection() 메서드 ★ - 교집합. (= Set의 공통요소 반환. = …
set Python - set.intersection_update() 메서드 - Set 공통요소 아닌 요소 제거. …
12/24
목록
찾아주셔서 감사합니다. Since 2012