Python - Exception

2020. 9. 2. 20:25Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# test7.py
# 예외처리 : 논리적오류, 물리적 오류 발생 처리
 
print("프로그램 시작")
a=4
b=0
if b!=0:
    print(a/b)  # ZeroDivisionError: division by zero
else:
    print("0으로 나뉨")
print("프로그램 끝")
 
print("프로그램 시작")
try:
    print(a/b)
except ZeroDivisionError as e:
    print(e)
finally:
    print("예외상관없이 마무리")
print("프로그램 끝")
 
print("프로그램 시작2")
a=[1,2,3]
try:
    print(a[3])
except IndexError as e:  # IndexError : list index out of range
    # print(e)
# 오류발생 -> 회피
    pass
finally:
    print("매무리")
print("프로그램 끝2")
 
# 오류 임의로 발생시키기
class Bird:
    def fly(self):
        raise NotImplementedError # 오류 임의로 발생
# b=Bird()
# b.fly()
 
# 클래스 Eagle Bird 상속
# fly90 메서드 오버라이딩 후 출력 fly() 메서드 오버라이딩
class Eagle(Bird):
    def fly(self):
        print("fly() 메서드 오버라이딩")
 
e=Eagle()
e.fly()
cs

 

예외처리를 배워보았는데 자바와 구조는 다를 게 없지만 문법적으로 처음 접하다 보니 좀 어색해서 처음엔 catch는 어디 갔지..? 하고 있었지만 다른 언어이고 훨씬 심플한 게 있어서 오히려 좋았다. class에도 사용 가능했던 pass는 여기서는 오류가 발생했을 때 아무것도 하지 않겠다 로 사용되었고 어려운 건 없고 어색할 뿐이었다.

'Python' 카테고리의 다른 글

Python - 모듈  (0) 2020.09.02
Python - 파일 입출력, print(),input()  (0) 2020.09.02
Python - class,상속  (0) 2020.09.02
Python - def(함수),lambda(람다함수)  (0) 2020.09.02
Python - for문,while 문  (0) 2020.08.21