programming/Python

Python // 예외처리

깨래 2017. 12. 7. 14:18

* 예외처리 


프로그램 작성시 작성자가 의도하지 않은 동작, 혹은 예상치 못한 오류에 대한 처리가 필요하다.

동작의 오류 뿐만이 아니라, 사용자가 의도하지 않은 상황에 대한 제한에 사용된다.


* try, except문


try :

# 문제가 없을 경우 실행

except :

# 문제가 생겼을 때 실행


try블록중 오류가 발생하면 except블록이 수행

try블록에서 오류가 발생하지 않으면 except블록은 수행되지 않는다.


ex)

1
2
3
4
5
try:
        num = int(input("Input the Number:"))
        print(num)
    except:
        print("###It's not number###")

cs

출력결과

Input the Number:2

2

Input the Number:5

5

Input the Number:a

###It's not number###

Input the Number:b

###It's not number###


정수형으로 입력을 받는 변수 num을 실행하는 문장인데, 정수가 아닌 문자가 들어가서 except가 실행이 된다.


여러 except 처리하기!


코드의 양이 늘어나면 처리해야 할 예외도 늘어난다. 늘어난 예외의 종류에 따른 예외처리를 구현하려면 하나 이상의 except절을 사용해야 한다.

try :

#문제가 없을 경우 실행

except 예외형식 1:

# 문제가 있을 경우 실행

except 예외형식 2:

# 문제가 있을 경우 실행


ex)   

1
2
3
4
5
6
7
8
9
10
try:
        num = int(input("input the number:"))
        divnum = int(input("input the number to divede:"))
        res= num/divnum
        print(res)
 
    except ValueError:
        print("you must input number")
    except ZeroDivisionError :
        print("can't divide with 0")

cs

출력결과

input the number:3

input the number to divede:1

3.0

input the number:3

input the number to divede:0   

can't divide with 0                0으로 나눌 수 없으므로 9행 except 실행

input the number:d

you must input number              정수만 넣을 수 있으므로 7행 except 실행

input the number:3

input the number to divede:d       정수만 넣을 수 있으므로 7행 except 실행

you must input number


위의 예제를 쪼금만 바꾸어서 예외처리를 하면서, 원래의 오류볼 수 있는 방법이 있다. 


except 예외형식1 as e:

# 문제가 생겼을 때 실행할 코드


except의 as 뒤에 따라오는 e는 인스턴스의 식별자, 이름이다. 위의 예제를 조금 수정해보겠다.


ex)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
while True:
    try:
        num = int(input("input the number:"))
        divNum = int(input("input the number to divide:"))
        res = num / divNum
        print(res)
 
    except ValueError as e:
        print("You must input number")
        print("원래 에러메세지:",e)
 
    except ZeroDivisionError as f:
        print("can't divide with 0")
        print("원래 에러메세지:",f)

cs

출력결과

input the number:3

input the number to divide:0

can't divide with 0

원래 에러메세지: division by zero

input the number:a

You must input number

원래 에러메세지: invalid literal for int() with base 10: 'a'


try와 함께 사용하는 else도 있다. try의 else절은 코드블록 실행 중에 아무런 예외가 일어나지 않으면 실행된다. 


try :

#실행 할 코드블록

except :

# 예외처리 코드블록

else : 

# except절을 만나지 않았을 경우 실행하는 코드블록


ex)

1
2
3
4
5
6
7
8
9
10
my_list=[1,2,3]
 
try:
    num=int(input("input the number:"))
    print("mylist[%d]:%d" %(num,my_list[num]))
 
except Exception as e:
    print("An exception arises",e)
else :
    print("success")

cs

출력결과

input the number:2

mylist[2]:3

success    # except를 만나지 않아서 실행

input the number:10

An exception arises list index out of range


무슨일이 있어도 일어나는 finally

else는 except를 만나지 않으면 실행이 되었다. 하지만 finally는 만나든 안만나든 무조건 실행이 된다.


ex)

1
2
3
4
5
6
7
8
while True:
    try:
        num = int(input("Input the Number:"))
        print(num)
    except:
        print("###It's not number###")
    finally:
        print("I Must do")

cs

출력결과

Input the Number:3

3

I Must do    # 무조건 실행

Input the Number:a

###It's not number###

I Must do    # 무조건 실행

Input the Number:0

0

I Must do    # 무조건 실행


예외형식은 거의 모두 Exception클래스로부터 상속을 받는다. 상속의 이러한 특징에 의해 ZeroDivisionError, IndexError은 Exception 클래스로 간주되므로 Exception클래스에 대한 예외 처리절이 다른 예외 처리절 앞에 위치하면 나머지 예외 처리절들을 모두 무시하는 일이 생긴다.!!


ex)

1
2
3
4
5
6
7
8
9
10
11
12
my_list=[1,2,3]
 
try:
    num=int(input("input the number:"))
    print(my_list[num]/0)
 
except Exception as e:
    print("An exception arises",e)
except ZeroDivisionError as e:
    print("Can't divide with 0",e)
except IndexError as e:
    print("go Wrong",e)

cs

출력결과

input the number:10

An exception arises list index out of range

input the number:2

An exception arises division by zero


결과 모두 Exception의 예외가 발생한다.


*rasie

일부러 오류를 발생시켜야 할 경우 사용된다.