티스토리 뷰

Python

에러 처리에 대한 기초 지식

techbard 2015. 7. 9. 14:30
  • Exceptions Handling in Python

1. What are Exceptions

Runtime Errors: File Not Found, Divide by Zero, Invalid Input etc.


2. Uncaught Exceptions


3. Python: try -- Except -- else


4. We can catch exception and also get Python Error Message


5. Python Documentation

https://docs.python.org/3/library/exceptions.html

  • 에러처리

# 단 하나의 에러에 대해서만 로직으로 처리하는 경우

l = ['apple', 'bannana', 'pear']


if 'apple' in l:

print('apple is in a list')

else:

print('apple is in not a list')


결과)

apple in a list


# 구조적으로 에러에 대비할 수 있다.

l = ['apple', 'bannana', 'pear']


def IsIn(num):

try:

fruit = l[num]

except Exception as e:

result = 'Index ' + str(num) + ' is not in a list.'

print(e)

else:

result = 'Index ' + str(num) + ' is in a list.'

finally:

print(result)


IsIn(0)


결과)

Index 0 is in a list.


# 어떤 에러가 발생했을까?

l = ['apple', 'bannana', 'pear']


def IsIn(num):

try:

fruit = l[num]

except Exception as e:

result = 'Index ' + str(num) + ' is not in a list.'

print(e)

else:

result = 'Index ' + str(num) + ' is in a list.'

finally:

print(result)


IsIn(3)


결과)

list index out of range

Index 3 is not in a list.


https://www.python.org/dev/peps/pep-0473/#indexerror



# 좀더 정확하게 원하는 에러를 처리해 보자.

l = ['apple', 'bannana', 'pear']


def IsIn(num):

try:

fruit = l[num]

except IndexError as e:

result = 'Index ' + str(num) + ' is not in a list.'

print(e)

else:

result = 'Index ' + str(num) + ' is in a list.'

finally:

print(result)


IsIn(3)


결과)

list index out of range

Index 3 is not in a list.

 

# 사용자 정의 에러를 발생시켜 로지컬하게 사용

def whatsYourName():
    yourName = 'mike'
    # yourName = '111'
    if yourName.isalpha():
        print('Your name is', yourName)
    else:
        raise Exception("Enter the alpha character.")

try:
    whatsYourName()
except Exception as e:
    print("Error:", e)

 

결과)

Your name is mike

 

def whatsYourName():
    # yourName = 'mike'
    yourName = '111'
    if yourName.isalpha():
        print('Your name is', yourName)
    else:
        raise Exception("Enter the alpha character.")

try:
    whatsYourName()
except Exception as e:
    print("Error:", e)

 

결과)

Error: Enter the alpha character.


# 사용자 정의 에러를 발생시켜 로지컬하게 사용 #2

def my_func(s):

    if s.isdigit():

        print('You entered a digit character.')

    else:

        raise Exception("Enter the number character.")


try:

    my_func('a')

except Exception as e:

    print(e)


결과)

Enter the number character.


  • Exceptions not Errors

# Not all exceptions due to error situation


- KeyboardInterrupt Exception

: User pressed ^C


- SystemExit Exception

: Request termination of interpreter


- StopIteration Exception

: No more objects to iterate over

: Loop completed


- Warning Exceptions

: Warnings not as serious as "real errors"

: Used to indicate deprecation, etc.

: See warnings module documentation


댓글
댓글쓰기 폼
공지사항
Total
410,766
Today
35
Yesterday
44
«   2019/12   »
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        
글 보관함