# Exceptions
try:
result = 1 / 0
except Exception as e:
print(f"'{e}' error occurred!")
lst = [1, 2, 3]
try:
print(lst[3])
except Exception as e:
print(f"'{e}' error occurred!")
# 결과
'division by zero' error occurred!
'list index out of range' error occurred!
# Try, except, else
# - The else block in a try statement is executed only if
# no exceptions are raised in the try block.
# Try, except, else, finally
# - The finally block is particularly useful for cleanup actions
# that must be executed under all circumstances, such as closing
# a file or releasing resources.
# Defining a Custom Exception
class NegativeValueError(Exception):
def __init__(self, msg):
self.msg = msg
super().__init__(self.msg)
def check_positive(number):
if number < 0:
raise NegativeValueError("The number is negative.")
try:
check_positive(10)
check_positive(-1)
except NegativeValueError as e:
print(f"Caught an exception: {e.msg}")
# 결과
Caught an exception: The number is negative.
# 간단한 함수를 하나 만든다.
def exceptionHandling():
a = 10
b = 2
c = (a / b)
print(c)
exceptionHandling()
# 결과
5.0
# 0으로 나누기 에러를 만들어 본다.
def exceptionHandling():
a = 10
b = 0
c = (a / b)
print(c)
exceptionHandling()
# 결과
ZeroDivisionError: division by zero
# 타입 에러를 만들어 본다.
def exceptionHandling():
a = 10
b = "string"
c = (a / b)
print(c)
exceptionHandling()
# 결과
TypeError: unsupported operand type(s) for /: 'int' and 'str'
# 타입 에러에 대한 예외 처리를 만든다.
def exceptionHandling():
try:
a = 10
b = "string"
c = (a / b)
print(c)
except TypeError:
print("Can't divide by string ")
exceptionHandling()
# 결과
Can't divide by string
# 0으로 나누기 에러에 대한 예외 처리를 만든다.
def exceptionHandling():
try:
a = 10
b = 0
c = (a / b)
print(c)
except TypeError:
print("Can't divide by string ")
except ZeroDivisionError:
print("Zero Division")
exceptionHandling()
# 결과
Zero Division
# 에러에 대한 공통 예외 처리를 만든다.
def exceptionHandling():
try:
a = 10
b = 0
c = (a / b)
print(c)
except:
print("In the except block")
exceptionHandling()
# 결과
In the except block
# 또 다른 에러에 대해 공통 예외 처리가 적용되는지 확인한다.
def exceptionHandling():
try:
a = 10
b = "string"
c = (a / b)
print(c)
except:
print("In the except block")
exceptionHandling()
# 결과
In the except block
# 에러가 없을 경우 실행하는 로직을 정의할때
def exceptionHandling():
try:
a = 10
b = 2
c = (a / b)
print(c)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
exceptionHandling()
# 결과
5.0
Because there was no exception, else is executed
# 에러가 있던, 없든 간에 무조건 실행하는 로직을 정의할때
## 에러 없을 경우
def exceptionHandling():
try:
a = 10
b = 2
c = (a / b)
print(c)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
finally:
print("Finally, always executed")
exceptionHandling()
# 결과
5.0
Because there was no exception, else is executed
Finally, always executed
## 에러 있을 경우
def exceptionHandling():
try:
a = 10
b = 0
c = (a / b)
print(c)
except:
print("In the except block")
else:
print("Because there was no exception, else is executed")
finally:
print("Finally, always executed")
exceptionHandling()
# 결과
In the except block
Finally, always executed
# 예외 문구를 담는 변수 이용
t = (1, 2, 3)
try:
t.append(4)
except AttributeError as e:
print("Error formed: ", e)
# 결과
Error formed: 'tuple' object has no attribute 'append'
# 기본적인 에러 예외 처리
result= None
x = int(input('number 1: '))
y = int(input('number 2: '))
try:
result = x / y
except Exception as e:
print(e)
# this will be executed only when we dont have any exception
else:
print('inside else')
# this will be executed for both the cases when we executed only
finally:
print('inside finally')
print('result = ', result)
# 결과
number 1: 10
number 2: 0
division by zero
inside finally
result = None
class Coffee:
def __init__(self, temperature):
self.__temperature = temperature
def drink_coffee(self):
if self.__temperature > 50:
print('Hot to drink.')
# Or
raise Exception('Coffee too hot.')
elif self.__temperature < 20:
print('Cold to drink.')
else:
print('Coffee OK to drink.')
cup = Coffee(100)
cup.drink_coffee()
# 결과
...
raise Exception('Coffee too hot.')
Exception: Coffee too hot.
class CoffeeException(Exception):
def __init__(self, arg):
self.msg = arg
class CoffeeWithMyException:
def __init__(self, temperature):
self.__temperature = temperature
def drink_coffee(self):
if self.__temperature > 50:
raise CoffeeException('Coffee too hot.')
elif self.__temperature < 20:
CoffeeException('Cold to drink.')
else:
print('Coffee OK to drink.')
cup = CoffeeWithMyException(50)
cup.drink_coffee()
cup = CoffeeWithMyException(80)
cup.drink_coffee()
# 결과
Coffee OK to drink.
...
raise CoffeeException('Coffee too hot.')
CoffeeException: Coffee too hot.
# equation solver
#
# a * x + b = c는
# 1) a * x + b - b = c - b
# 2) a * x = c - b
# 3) a * x / a = (c - b) / a
# 4) x = (c - b) / a
def solve_equation(a: float, b: float, c: float) -> float:
try:
return (float(c) - float(b)) / float(a)
except (ZeroDivisionError, ValueError):
print('Error! Enter a valid value.')
raise
print('ax + b = c linear equation solver')
a = input('Enter a: ')
b = input('Enter b: ')
c = input('Enter c: ')
try:
x = solve_equation(a, b, c)
except Exception:
print('Something bad happened.')
else:
print(f'x is {x}')
# 결과
ax + b = c linear equation solver
Enter a: 10
Enter b: 2
Enter c: 5
x is 0.3
Enter a: 0
Enter b: 3
Enter c: 6
Error! Enter a valid value.
Something bad happened.
Enter a: a
Enter b: 5
Enter c: 6
Error! Enter a valid value.
Something bad happened.
# when to use try-except
# if somekey in d:
# extract_data(d)
# else:
# skip_this_one(d)
# versus
# try:
# extract_data(d)
# except:
# skip_this_one(d)
# in general, when using a try-except or deciding whether to use if/else,
# it's better to be as specific as possible.
# So, if it's one particular key that you know is either going to be
# there or not there, I'd use an if/else.
# If I don't know what might go wrong but
# I know that something might go wrong,
# so a dictionary might be in a different format than I'm expecting,
# then I might use a try-except.
# try - except의 예
import sys
total: float = 0
while True:
user_input: str = input("Enter a number: ")
if user_input == '0':
print(f"Total: {total}")
sys.exit()
try:
total += float(user_input)
except ValueError:
print("Invalid... try again.")
# 결과
Enter a number: 10
Enter a number: -5
Enter a number: a
Invalid... try again.
Enter a number: 0
Total: 5.0
# The difference netween a beginner and a professional
# is that a professional has run into practically
# every error that has ever existed, meaning that
# if something ever goes wrong in a program, they're
# going to be able to identify that error and
# fix it immediately because they know exactly what it was
# due to their experience with all these errors.
def check_age(age: int) -> bool:
if age < 0:
raise ValueError("Not a valid age...")
elif age >= 19:
print("You are old enough!")
return True
else:
print("You are not old enough...")
return False
check_age(10)
check_age(20)
check_age(-1)
# 결과
You are not old enough...
You are old enough!
...
ValueError: Not a valid age...
import string
import sys
def is_letters_only(text: str) -> None:
alphabet: str = string.ascii_letters + " "
for char in text:
if char not in alphabet:
raise ValueError("Text can only contain letters from the alphabet!")
print(f"'{text}' is letters-only, good job!")
def main() -> None:
while True:
try:
user_input: str = input("Check text: ('exit' to quit)")
if user_input == 'exit':
sys.exit()
is_letters_only(user_input)
except ValueError:
print("Please only enter English letters...")
except Exception as e:
print(f"Encounted and unknown exception: {type(e)}, {e}")
main()
# 결과
Check text: ('exit' to quit)hello
'hello' is letters-only, good job!
Check text: ('exit' to quit)hello!
Please only enter English letters...
Check text: ('exit' to quit)exit
# Take advantage of each block
#
# try:
# # Do something
# except MyException as e:
# # Handle exception
# else:
# # Runs when there are no exceptions
# finally:
# # Always runs after try:
import json
def load_json_key(data, key):
try:
result_dict = json.loads(data)
except ValueError as e:
raise KeyError from e
else:
return result_dict[key]
def main():
try:
# load_json_key('{"foo": bad payload}', 'foo')
print(load_json_key('{"foo": "bar"}', 'foo'))
# assert False
except KeyError:
print("Saw KeyError")
main()
# 결과
bar
def ask_for_int():
while True:
try:
result = int(input("Please provide number: "))
except:
print("Whoops! That is not a number")
continue
else:
print("Yes thank you")
break
finally:
print("End of try/except/finally")
ask_for_int()
# Output:
Please provide number: asas
Whoops! That is not a number
End of try/except/finally
Please provide number: 11
Yes thank you
End of try/except/finally
def ask():
waiting = True
while waiting:
try:
n = int(input("Enter a number"))
except:
print("Please try again! \n")
continue
else:
waiting = False
ask()
# Output:
Enter a number11
try:
age = int(input("Enter your age: "))
print(f"Next year, you will be {age+1} years old.")
except ValueError:
print(f"That's not a valid age!")
# Output:
Enter your age: 10
Next year, you will be 11 years old.
try:
with open('nonexistent.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("The file does not exist.")
except IOError:
print("An error occurred while reading the file.")
# Output:
The file does not exist.
댓글 영역