파이썬3 바이블 - 제17장 연습문제

프리렉 - FREELEC

http://freelec.co.kr/book/catalogue_view.asp?UID=134

이강성저

1.

In [1]:
try:
    price = selected
except NameError as err:
    price = 0

print (price)
0

2.

2번 문제는 파이썬3에 적절하지 않은 문제라 답변을 생략합니다.

3.

다음과 같이 사용자 예외를 정의하고 예외가 발생했을 때 처리할 수 있습니다. 예외 클래스는 super()를 이용해서 초기화 할 수 있으며, 이 때 전달된 인수들은 인스턴스의 args 속성 값으로 확인이 가능합니다.

In [2]:
class MyException(Exception):
    def __init__(self, message, dur):
        super().__init__(message, dur)
    def __str__(self):
        return '{} - {}'.format(self.__class__.__name__, self.args)
In [3]:
try:
    raise MyException('msg', 10)
except MyException as a:
    print(a.args)
    print (a)
('msg', 10)
MyException - ('msg', 10)

4.

In [4]:
import traceback

try:
    a = noname
except NameError as err:
    print('ready to save the error message to traceback_msg.txt')
    s = traceback.print_exc(file=open('traceback_msg.txt', 'w'))
ready to save the error message to traceback_msg.txt

In [5]:
!cat traceback_msg.txt
Traceback (most recent call last):
  File "<ipython-input-4-84da80c686a2>", line 4, in <module>
    a = noname
NameError: name 'noname' is not defined

In [5]: