Exception objects

Syntax for creating a new exception object

new Exception($message [, $code])

The syntax for the throw statement

throw $exception;

A function that may throw an exception

function calculate_future_value($investment, $interest_rate, $years) {
if ($investment <= 0 || 
  $interest_rate <= 0 || 
  $years <= 0 ) {
  throw new Exception(
    "All arguments must be greater than zero.");
  }
  $future_value = $investment;
  for ($i = 1; $i <= $years; $i++) {
    $future_value += 
    $future_value * $interest_rate * .01; 
  }
  return round($futureValue, 2);
}

A statement that causes an exception

$futureValue = calculate_future_value(10000, 0.06, 0);

Back