상세 컨텐츠

본문 제목

에러 처리에 대한 기초 지식

Python

by 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


반응형

관련글 더보기

댓글 영역