Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Throwing Exceptions in Your Code | Custom Exceptions and Advanced Handling
PHP Error Handling and Exceptions

bookThrowing Exceptions in Your Code

Deslize para mostrar o menu

When you need your PHP code to signal that something has gone wrong—such as an invalid value or an unexpected state—you use the throw keyword. Throwing an exception allows you to halt normal execution and transfer control to the nearest catch block, where you can handle the problem in a controlled way. The throw keyword is used to create and send an exception object, which can carry information about what went wrong. This is essential for building robust applications that can respond gracefully to errors.

throw_example.php

throw_example.php

copy
12345678910111213141516171819
<?php function divide($numerator, $denominator) { if (!is_numeric($numerator) || !is_numeric($denominator)) { throw new Exception("Both arguments must be numbers."); } if ($denominator == 0) { throw new Exception("Cannot divide by zero."); } return $numerator / $denominator; } try { echo divide(10, 2); // Outputs: 5 echo "\n"; echo divide(10, 0); // Will throw an exception } catch (Exception $e) { echo "Caught exception: " . $e->getMessage(); } ?>

Looking closely at the divide function, you can see how input validation is performed before any calculation happens. The function first checks if both arguments are numbers. If not, it throws an Exception with a clear message. Next, it checks if the denominator is zero—a situation that would cause a runtime error if not handled. Instead of letting the program crash, the function throws another Exception to signal the problem. The try block demonstrates how you can catch and respond to these exceptions, keeping your program in control even when something goes wrong.

propagate_exception.php

propagate_exception.php

copy
1234567891011121314151617181920
<?php function processUserInput($input) { if (empty($input)) { throw new Exception("Input cannot be empty."); } // Some processing logic here return strtoupper($input); } function main() { try { $result = processUserInput(""); // This will throw echo $result; } catch (Exception $e) { echo "Error: " . $e->getMessage(); } } main(); ?>

Throwing exceptions is a powerful way to signal serious problems that should not be ignored, such as invalid arguments or unexpected conditions. Unlike returning false or an error code, throwing an exception forces the caller to deal with the problem, or let it propagate up the call stack to a higher-level handler. This makes your code more robust and less likely to fail silently. However, for expected, minor issues—such as a missing optional value—returning false or an error code might be more appropriate. Use exceptions when you want to enforce correct usage and ensure that problems are handled explicitly.

1. What does the throw keyword do in PHP?

2. Why might you want to throw an exception instead of returning false?

question mark

What does the throw keyword do in PHP?

Select the correct answer

question mark

Why might you want to throw an exception instead of returning false?

Select all correct answers

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 2. Capítulo 3
some-alt