티스토리 뷰

Exception(예외)

  • 프로그램 수행 중에 발생할 수 있는 error로 사전에 프로그래머가예상해서 처리할 수 있는 가벼운 에러를 말한다.

  • 예외처리를 이용해서 프로그램이 더이상 수행할 수 없는 상황이 발생 했을 때 무조건 프로그램을 종료하지 않고 적절히 대처하여 실행을 계속하도록 프로그램을 작성한다.

Exception Handling(예외처리)

  • try ~ exception, try ~ else, try ~ finally, try ~ else ~ finally

try :
	< code block >
except 예외종류, 예외변수 : # 생략가능
	< 예외 발생시 실행되는 문구 >
else :
	< 예외가 발생하지 않았을 때 실행되는 문구 >
finally :
	< 예외 발생 여부에 관계 없이 실행되는 문구 >
print('프로그램 실행')

try:
    print('나눗셈 시작')
    10 / 0
    print('나눗셈 끝')
except ZeroDivisionError as e:
    print('예외 발생~')
    print(e)
    print(format(type(e)))
    print(format(e.args))
    print(format(e))

print('프로그램 실행 중')

l = [1, 2, 3]

def func1():
    try:
        num = l[0]
    except IndexError:
        print('IndexError')
    else:
        print('Keep calm and go ahead')

if __name__ == '__main__':
    func1()

사용자 Exception

  • 사용자 정의 예외를 만들기 위해서는 Exception 클래스를 상속

  • raise 를 이용하여 객체를 호출

  • raise 는 에러를 강제로 발생시킬 수 있는 키워드이다.

class MyException(Exception):
    def __init__(self, value):
        self.value = value
    
    def __str__(self):
        return 'ㅊㅋㅊㅋ' + self.value

def raise_exception(err_msg):
    raise MyException(err_msg)

try:
    raise_exception('Error~~~~')
except MyException as e:
    print(e)

  • \__str__

class Person:
    def __init__(self, name, age, phone):
        self.name = name
        self.age = age
        self.phone = phone

    def __str__(self):
        s = f'이름: {self.name}\n'
        s += f'나이: {self.age}, 전화번호: {self.phone}'
        return s

    # def show_info(self):
    #     print(f'이름: {self.name}')
    #     print(f'나이: {self.age}, 전화번호: {self.phone}')

king = Person('세종', '23', '010-1234-1234')
print(king)

예외 테스트 assert 와 unittest

  • assert

    특정 조건을 충족하는 경우에만 예외를 발생시킬 때 유용

  • assert <조건식> <메시지>

def check_assert():
    a = 3
    b = 2
    assert a < b, "False: 'a'가 'b'보다 크다"
    print(f'a = {a}, b = {b}')

try:
    check_assert()
except Exception as e:
    print(f'Exception: check_assert {e}')

  • unittest

    파이썬의 표준 패키지로 수행되는 코드 및 프로그램을 단위로 테스트 하기 위한 모듈

  • 단위테스트 : 정의된 클래스의 함수 단위로 함수의 반환 값과 기대 값으 비교하여 테스트

import unittest
class MyTest(unittest.TestCase):
    def test1(self):
        print('test1')

    def test2(self):
        print('test2')
        assert True == True

if __name__ == '__main__':
    TS = unittest.TestSuite()
    TS.addTest(MyTest('test1'))
    TS.addTest(MyTest('test2'))
    TS2 = unittest.makeSuite(MyTest, 'test')

    unittest.main()

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함