Exception
Exception
An error that occurs while a program is running. Handled with try-catch. Exception handling is key to stability.
Exception
An error that occurs while a program is running. Handled with try-catch. Exception handling is key to stability.
An Exception is an object that represents an unexpected situation or error that occurs while a program is running. When an abnormal condition that deviates from the normal program flow occurs, an exception is thrown, and if it is not handled properly, the program terminates abnormally.
Exception handling is done through the try-catch-finally construct. Code that may cause an exception is executed in the try block, the exception that occurred is caught and handled in the catch block, and cleanup code that must always run regardless of whether an exception occurred is written in the finally block.
Most programming languages provide a hierarchical exception class structure. In Java, Throwable is at the top, with Error and Exception beneath it, and in Python, Exception sits under BaseException. Developers can inherit from these base classes to define custom exceptions and express domain-specific errors.
In practice, exception handling is key to system stability and user experience. With proper exception handling, a program can behave gracefully even in error situations, deliver meaningful error messages to users, and log the information needed for debugging.
# Python 예외 처리 예제
# 1. 기본 try-catch-finally 구문
def divide(a, b):
try:
result = a / b
return result
except ZeroDivisionError as e:
print(f"오류: 0으로 나눌 수 없습니다 - {e}")
return None
except TypeError as e:
print(f"오류: 잘못된 타입입니다 - {e}")
return None
finally:
print("연산 시도 완료")
print(divide(10, 2)) # 출력: 연산 시도 완료 → 5.0
print(divide(10, 0)) # 출력: 오류: 0으로 나눌 수 없습니다 → None
# 2. 커스텀 예외 클래스 정의
class ValidationError(Exception):
"""유효성 검사 실패 시 발생하는 커스텀 예외"""
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
class User:
def __init__(self, email, age):
self.email = self.validate_email(email)
self.age = self.validate_age(age)
def validate_email(self, email):
if '@' not in email:
raise ValidationError('email', '유효한 이메일 형식이 아닙니다')
return email
def validate_age(self, age):
if not isinstance(age, int) or age < 0 or age > 150:
raise ValidationError('age', '나이는 0-150 사이의 정수여야 합니다')
return age
# 사용 예시
try:
user = User('invalid-email', 25)
except ValidationError as e:
print(f"유효성 검사 실패: {e.field} - {e.message}")
# 3. 예외 체이닝과 컨텍스트 관리자
class DatabaseConnection:
def __enter__(self):
print("DB 연결 열기")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("DB 연결 닫기")
return False # 예외를 다시 발생시킴
def query(self, sql):
if "DROP" in sql.upper():
raise PermissionError("DROP 명령어는 허용되지 않습니다")
return f"쿼리 실행: {sql}"
# with 문으로 안전한 리소스 관리
try:
with DatabaseConnection() as db:
result = db.query("SELECT * FROM users")
print(result)
result = db.query("DROP TABLE users") # 예외 발생
except PermissionError as e:
print(f"권한 오류: {e}")
# 출력: DB 연결 열기 → 쿼리 실행... → 권한 오류... → DB 연결 닫기
"The external API call was missing exception handling, so the entire service froze on a timeout. We need to wrap it in try-catch and add retry logic and a fallback response. Shall we also consider the circuit breaker pattern?"
"The difference between a Checked Exception and an Unchecked Exception is whether they are checked at compile time. A Checked Exception must be handled, while an Unchecked one inherits from RuntimeException and is handled optionally. In general, use Checked for recoverable situations and Unchecked for programming errors."
"The catch block catches Exception too broadly, and there's no logging either. Please branch by specific exception type and leave at least an error log. If you swallow exceptions, debugging becomes impossible."
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
If you leave a catch block empty, you cannot tell when an exception occurs. At the very least, log it or perform an appropriate fallback action. Even when it should be ignored, state the reason in a comment.
Catching all exceptions at once, as in `catch (Exception e)`, hides unexpected bugs. Catch only the specific exception types you can handle, and propagate the rest upward.
Exceptions are meant for exceptional situations. Using try-catch for normal branching causes performance degradation and readability problems. Check in advance with conditional statements.
Always clean up files, DB connections, network sockets, and the like using a finally block, try-with-resources (Java), the with statement (Python), or defer (Go). Resource leaks lead to memory problems.