Backend/Python

Python 파이썬 예외 처리 모듈 traceback

쏠솔랄라 2023. 7. 6. 10:50

 

 

traceback

 

: except로 처리할 때는 무슨 예외 인지 알기가 어렵기 때문에
어떤 예외 인지 파악할 수 있도록 만들어 주는 모듈

 


traceback.format_exc()
: 개발용 콘솔 로그
예외 발생시 발생되는 로그를 띄어주는 메소드

 

 

import traceback

while True:    
    try:
        a = int(input("정수 입력 : "))
        b = int(input("정수 입력 : "))
        if b == 0:
            raise ZeroDivisionError("0을 입력하실수 없습니다.")
        print("{} + {} = {}".format(a,b,a + b))
        print("{} - {} = {}".format(a,b,a - b))
        print("{} × {} = {}".format(a,b,a * b))
        print("{} ÷ {} = {}".format(a,b,a / b))
    except ValueError as value:
        print(value.with_traceback(None))
        print("정수만 입력하셔야 합니다.")
    except:
        #print(traceback.format_exc())
        traceback.print_exc()

 

 

예외 클래스 생성

 

: 예외 클래스 만들기

모든 예외 클래스는 Exception 클래스를 상속받았다

 

 

import traceback

class MyError(Exception):
    
    def __init__(self, *args: object,code = 0) -> None:
        super().__init__(*args)
        self.__code = code

    def codePrint(self):
        if self.__code == 0:
            return "정상입니다."
        elif self.__code == 1:
            return "0을 입력하실수 없습니다."
        elif self.__code == 2:
            return "음수를 입력하실수 없습니다."

while True:    
    try:
        a = int(input("정수 입력 : "))
        b = int(input("정수 입력 : "))
        if b == 0:
            #raise MyError("0을 입력하실수 없습니다.")
            raise MyError(code=1)
        elif a <= 0 or b<0:
            raise MyError(code=2)
        print("{} + {} = {}".format(a,b,a + b))
        print("{} - {} = {}".format(a,b,a - b))
        print("{} × {} = {}".format(a,b,a * b))
        print("{} ÷ {} = {}".format(a,b,a / b))
    except ValueError as value:
        print("정수만 입력하셔야 합니다.")
    except MyError as e:
        #print(traceback.format_exc())
        #print(e.__str__())
        print(e.codePrint())

 

 


 

 

Exercise1

 

 

예외 처리를 이용하여 아래의 내용을 구현하세요

사용자에게 닉네임을 입력받도록 하겠습니다
아래의 2가지 조건에 어긋날 경우 오류 출력

[1] 3~10글자를 벗어나는 경우
    → 3~10글자 이내로 작성하세요
[2] 운영자라는 단어가 포함된 경우
    → 운영자라는 단어는 포함할 수 없습니다

 

 

import traceback

class Error(Exception):
    
	def __init__(self, *args: object, errorCode=0, nickname=None) -> None:
		super().__init__(*args)
		self.__errorCode = errorCode
		self.__nickname = nickname

	def errorCode(self):
		if self.__errorCode==0:
			return "3~10 글자 사이로 입력할 수 있습니다"

		if self.__errorCode==1:
			return "운영자라는 단어는 포함할 수 없습니다"

	def disp():
		print("생성된 닉네임은 '{}' 입니다".format(nickname))

while True:

	try:
		nickname = input("닉네임 입력 : ")

		if nickname.__len__()<3 or nickname.__len__()>10:
			raise Error(errorCode=0)
		
		if '운영자' in nickname:
			raise Error(errorCode=1)
	
		else:
			print("닉네임이 생성되었습니다.")
			break

	except ValueError as value:
		print()
	except Error as e:	
		print(e.errorCode())

 

 

출력화면

 

while만 사용한 풀이

while True:
    try:
        nick = input("닉네임 입력 : ")

        if nick.__len__() < 3 or nick.__len__() > 10:   
            raise Exception("3~10글자 이내로 작성하세요")
        elif nick.find("운영자") != -1:
            raise Exception("운영자라는 단어는 포함시킬 수 없습니다")
    except Exception as e:
        print(e)
    else:
        print("닉네임 : {}".format(nick))
        break

 

 

class를 사용한 풀이

class MyError(Exception):

    def __init__(self, *args: object,code) -> None:
        super().__init__(*args)
        self.__code = code

    def codePrint(self):
        if self.__code == 0:
            return "정상입니다."
        elif self.__code == 1:
            return "3~10글자 이내로 작성하세요"
        elif self.__code == 2:
            return "운영자라는 단어는 포함시킬 수 없습니다"

    @property
    def code(self):
        return self.__code

while True:
    try:
        nick = input("닉네임 입력 : ")

        if nick.__len__() < 3 or nick.__len__() > 10:   
            raise MyError(code = 1)
        elif nick.find("운영자") != -1:
            raise MyError(code = 2)
    except MyError as e:
        print(e.codePrint())
        if e.code != 2:
            try:
                if nick.find("운영자") != -1:
                    raise MyError(code = 2)
            except MyError as e:
                print(e.codePrint())
    else:
        print("닉네임 : {}".format(nick))
        break