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.
# 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
댓글 영역