예외 클래스
Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 66번째.
PHP에서 예외는 실행 중에 문제가 발생했음을 알리는 데 사용되는 객체입니다. 모든 예외의 기본 클래스는 Exception이며, 그 구조를 이해하면 OOP 애플리케이션에서 오류를 효과적으로 처리하는 데 도움이 됩니다.
예외를 발생시키면, 무엇이 잘못되었는지 설명하는 메시지와 함께 Exception 클래스(또는 하위 클래스)의 인스턴스를 생성합니다:
<?php
class BankAccount {
public function __construct(private float $balance = 0) {}
public function withdraw(float $amount): float {
if ($amount > $this->balance) {
throw new Exception("Insufficient funds");
}
$this->balance -= $amount;
return $amount;
}
}
$account = new BankAccount(100);
$account->withdraw(150);
그러면 "Insufficient funds"라는 메시지와 함께 처리되지 않은 예외 오류가 발생합니다.
PHP는 다양한 상황에 사용할 수 있는 여러 내장 예외 클래스를 제공합니다. InvalidArgumentException은 잘못된 입력을 나타내고, RuntimeException은 실행 중 발생한 오류를 나타내며, LogicException은 프로그래밍 오류를 나타냅니다.
<?php
class Calculator {
public function divide(int $a, int $b): float {
if ($b === 0) {
throw new InvalidArgumentException("Cannot divide by zero");
}
return $a / $b;
}
}
모든 예외 객체에는 유용한 정보가 담겨 있습니다. getMessage()는 오류 메시지를 반환하고, getCode()는 선택적 오류 코드를 반환하며, getFile()과 getLine()은 예외가 발생한 위치를 알려 줍니다. 구체적인 예외 유형을 사용하면 코드의 의도가 더 명확해지고 오류를 더 정밀하게 처리할 수 있습니다.
챌린지
쉬움서로 다른 유형의 문제를 알리기 위해 PHP의 내장 exception 클래스를 사용하는 inventory management system을 만들어 봅시다. 특정하고 의미 있는 방식으로 실패할 수 있는 product inventory를 만들게 됩니다.
코드를 세 개의 파일로 구성합니다:
Product.php: inventory의 항목을 나타내는Productclass를 만듭니다. public$sku(string), public$name(string), private$quantity(int)에 constructor promotion을 사용합니다. class에는 다음이 있어야 합니다:- current quantity를 반환하는
getQuantity(): intmethod - quantity를 증가시키는
addStock(int $amount): voidmethod. amount가 1보다 작으면"Amount must be positive"message와 함께InvalidArgumentException을 throw합니다. - quantity를 감소시키는
removeStock(int $amount): voidmethod. amount가 1보다 작으면"Amount must be positive"message와 함께InvalidArgumentException을 throw합니다. amount가 current quantity를 초과하면"Insufficient stock"message와 함께RuntimeException을 throw합니다.
- current quantity를 반환하는
Inventory.php: product collection을 관리하는Inventoryclass를 만듭니다. Product file을 include합니다. class에는 다음이 있어야 합니다:- SKU로 indexed된 products를 저장할 private array
- product를 추가하는
addProduct(Product $product): voidmethod. 동일한 SKU를 가진 product가 already exists하면"Product already exists: [sku]"message와 함께LogicException을 throw합니다. - SKU로 product를 반환하는
getProduct(string $sku): Productmethod. found되지 않으면"Product not found: [sku]"message와 함께InvalidArgumentException을 throw합니다.
main.php: Inventory file을 include합니다. SKU, product name, operation("add","remove"또는"duplicate")이라는 세 가지 inputs를 받습니다.Inventory를 Create하고, given SKU, name, initial quantity10으로 새로운Product를 추가합니다.operation을 Based로 다음을 수행합니다:
"add": product에서addStock(5)를 Call한 다음"Stock updated: [quantity]"를 출력합니다."remove": product에서removeStock(15)를 Call합니다(이 operation은 exception을 throw해야 합니다)."duplicate": 동일한 SKU를 가진 another product를 추가하려고 합니다(이 operation은 exception을 throw해야 합니다).
exception이 throw되면 exception의 class name을
": "과 exception의 message에 followed하여 출력합니다. class name을 가져오기 위해 PHP의get_class()function을 사용합니다.
이 challenge는 서로 다른 exception type이 invalid input, runtime failures, logic errors 등 서로 다른 종류의 문제를 어떻게 전달하는지 보여 주며, 코드의 error handling을 더욱 precise하고 meaningful하게 만듭니다.
직접 해보기
<?php
require_once 'Inventory.php';
// 입력 읽기
$sku = trim(fgets(STDIN));
$name = trim(fgets(STDIN));
$operation = trim(fgets(STDIN));
try {
// TODO: Inventory 생성
// TODO: 주어진 SKU, name 및 초기 수량 10으로 Product 생성
// TODO: 제품을 inventory에 추가
// TODO: operation에 따라:
// - "add": Call addStock(5) on the product, then print "Stock updated: [quantity]"
// - "remove": 제품에 removeStock(15) 호출
// - "duplicate": 동일한 SKU로 다른 제품 추가 시도
} catch (Exception $e) {
// TODO: 예외 클래스 이름 뒤에 ": "와 메시지를 출력
// Hint: 클래스 이름을 얻으려면 get_class($e) 사용
}
?>이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
객체 지향 프로그래밍의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러