예외
를 별도 처리함으로써 프로그램 전체 실행에 문제가 없도록 하는 방법try
, except
키워드를 사용else
, finally
키워드는 생략 가능#예외 발생이 예상되는 구문 작성
try:
n1 = float(input('num1: '))
n2 = float(input('num2: '))
#예외 발생시 실행되는 구문 작성
except:
print('숫자가 아닙니다.')
#예외 발생하지 않은 경우 실행되는 구문 작성
else:
print(f'{n1} + {n2} = {n1 + n2}')
#예외 발생과 상관없이 항상 실행되는 구문
finally:
print(f'input data: {n1}, {n2}')
Exception
Class
try:
n1 = float(input('num1: '))
n2 = float(input('num2: '))
#as e: 'e'는 예외 발생시 생성된 실제 예외 객체를 참조함
except Exception as e:
print(e)
'''
숫자를 입력하지 않았을 때 출력값:
num1: d
could not convert string to float: 'd'
'''
raise
1) 예외를 발생시키는 키워드
class CustomError(Exception):
pass
x = 10
if x > 5:
raise CustomError("x should not be greater than 5")
2) exception class에 매개변수를 넣어서 원하는 문자열로 예외를 발생시킬 수 있음
def divCalculator(n1, n2):
if n2 != 0:
print(f'{n1} / {n2} = {n1/n2}')
else:
raise Exception('0으로 나눌 수 없습니다.')
num1 = int(input('input number1: '))
num2 = int(input('input number2: '))
try:
divCalculator(num1, num2)
except Exception as e:
print(f'Exception: {e}')
파이썬의 예외 처리 메커니즘
예외가 발생할 때 마다 해당 예외 클래스의
인스턴스가 생성
되고, 해당 인스턴스에는 예외에 관한 다양한 정보가 포함됨raise Exception("Something went wrong")
위의 코드는
1)Exception
클래스의 인스턴스를 생성하고
2)raise
로 이를 발생시킴
Exception Class의 정의(일부분)
class Exception(BaseException): """Common base class for all non-exit exceptions.""" def __init__(self, *args, **kwargs): self.args = args self.__dict__.update(kwargs) def __str__(self): return str(self.args) def __repr__(self): return repr(self.args)
__init__
: 예외 객체를 초기화하는 데 사용되며, 가변 개수의 위치 인수와 키워드 인수를 받아서 args 속성에 저장합니다. 키워드 인수는 예외 객체의 속성으로 추가됩니다.__str__
: 예외 객체를 문자열로 변환하는 메서드입니다. 이 메서드를 오버라이드하여 예외 객체를 문자열로 표현하는 방식을 변경할 수 있습니다.__repr__
: 예외 객체를 파이썬 표현식으로 나타내는 메서드입니다. 주로 디버깅 목적으로 사용됩니다.