- PHP try catch-finally example
- PHP try catch-finally example
- Syntax of try-catch-finally block in PHP
- Example 1: Using a try-catch-finally block to open and close a file
- Example 2: Using a try-catch-finally block to connect to a database
- Example 3: Using a try-catch-finally block to delete a file
- Example 4: Using try-catch-finally blocks to handle exceptions
- Example 5: Using a custom exception class
- Example 6: Rethrowing an exception
- Example 7: Catching Multiple Exceptions
- Conclusion
- PHP try…catch…finally
- Introduction to the PHP try…catch…finally statement
- PHP finally & return
- The try…finally statement
- Summary
- Исключения PHP: Try Catch для обработки ошибок
- Что такое исключение?
- Поток управления обработкой исключений
PHP try catch-finally example
A try-catch-finally block is an essential feature of PHP that enables developers to handle runtime errors and exceptions that may occur during the execution of a block of code. The try block allows you to test a piece of code that may throw an exception, while the catch block allows you to handle the exception in a controlled and graceful manner. Moreover, the finally block provides a way to execute a block of code after the try-catch block, even if an exception was thrown or not. This capability provides flexibility and reliability to your code, making it easier to handle errors and maintain your application’s stability.
In this article, you will learn how to use PHP try-catch-finally blocks. By the end of this article, you will have a solid understanding of what is try-catch-finally blocks in PHP and how to use them with practical examples.
PHP try catch-finally example
- Syntax of try-catch-finally block in PHP
- Example 1: Using a try-catch-finally block to open and close a file
- Example 2: Using a try-catch-finally block to connect to a database
- Example 3: Using a try-catch-finally block to delete a file
- Example 4: Using try-catch-finally blocks to handle exceptions
- Example 5: Using a custom exception class
- Example 6: Rethrowing an exception
- Example 7: Catching Multiple Exceptions
Syntax of try-catch-finally block in PHP
The try-catch-finally block in PHP has the following syntax:
try < //code that may cause an exception >catch(Exception $e) < //code to handle the exception >finally < //code to be executed after the try-catch block >
In the above syntax, the try block contains the code that may throw an exception. If an exception is thrown, the catch block catches the exception and handles it. The finally block contains the code to be executed after the try-catch block, regardless of whether an exception was thrown or not.
Example 1: Using a try-catch-finally block to open and close a file
The following example demonstrates how to use a try-catch-finally block to open and close a file:
catch(Exception $e) < echo "Error: " . $e->getMessage(); > finally < fclose($file); >?>
In example 1, you attempt to open a file called example.txt using the fopen() function. If an exception is thrown while opening the file using the above given code, Then catch block catches the exception and displays an error message on web page. The finally block closes the file using the fclose() function, regardless of whether an exception was thrown or not.
Example 2: Using a try-catch-finally block to connect to a database
The following example demonstrates how to use a try-catch-finally block to connect to a database:
catch(PDOException $e) < echo "Error: " . $e->getMessage(); > finally < $conn = null; >?>
In the above code, you attempt to connect to a database using the PDO() constructor. If an exception is thrown while connecting to the database, the catch block catches the exception and displays an error message. The finally statement closes the database connection using the null assignment operator, regardless of whether an exception was thrown or not.
Example 3: Using a try-catch-finally block to delete a file
The following example demonstrates how to use a try-catch-finally block to delete a file:
catch(Exception $e) < echo "Error: " . $e->getMessage(); > finally < //code to be executed after the try-catch block >?>
In the above code, you attempt to delete a file called example.txt using the unlink() function. If an exception is thrown while deleting the file, the catch block catches the exception and displays an error message. The finally block contains no code to be executed after the try-catch block.
Example 4: Using try-catch-finally blocks to handle exceptions
The following example demonstrates how to use a try-catch-finally block to handle an exception:
catch(Exception $e) < echo "Error: " . $e->getMessage(); > finally < echo "The code in the finally block is always executed."; >?>
Output: Error: Division by zero
The code in the finally statement is always executed.
In the above code, you attempt to divide the number 10 by zero, which is not allowed in PHP and will throw an exception. The catch block catches the exception and displays an error message using the getMessage() method of the Exception object. The finally block contains the code that should be executed regardless of whether an exception is thrown or not.
Example 5: Using a custom exception class
class CustomException extends Exception <> try < // some code that may throw a CustomException >catch (CustomException $e) < // handle the CustomException >finally < // code that will be executed regardless of whether an exception was thrown or not >
In this example, you define a custom exception class called CustomException that extends the Exception class. The catch block catches the CustomException and handles it.
Example 6: Rethrowing an exception
try < // some code that may throw an exception >catch (Exception $e) < // handle the exception throw $e; >finally < // code that will be executed regardless of whether an exception was thrown or not >
In this example, the catch block handles the exception and then rethrows it using the throw keyword. This permits the errors to be caught by another catch statement further up the call stack.
Example 7: Catching Multiple Exceptions
try < //code that may cause an exception >catch(DivisionByZeroError $e) < //code to handle a division by zero exception >catch(FileNotFoundException $e) < //code to handle a file not found exception >catch(Exception $e) < //code to handle any other exception >finally
In this example, You have three catch blocks to handle different types of exceptions. If a division by zero exception is thrown, the first catch block will handle it. If a file not found exception is thrown, the second catch block will handle it. If any other type of exception is thrown, the third catch block will handle it. The finally block is executed regardless of whether an exception is thrown or not.
Conclusion
In this article, you have learned how to use of try-catch-finally blocks in PHP with examples. You have seen how to handle errors that may happen during the execution of a block of code and how to run a block of code after the try-catch block, regardless of whether an error was thrown or not. By using try-catch-finally blocks in your PHP code, you can ensure that your
PHP try…catch…finally
Summary: in this tutorial, you’ll learn how to use the PHP try. catch. finally statement to handle exceptions and clean up the resources.
Introduction to the PHP try…catch…finally statement
The try…catch statement allows you to handle exceptions. When an exception occurs in the try block, the execution jumps to the catch block. In the catch block, you can place the code that handles the exception.
The following example uses the try…catch block to read a CSV file into an array:
$data = []; try < $f = fopen('data.csv', 'r'); while ($row = $fgetcsv($f)) < $data[] = $row; >fclose($f); > catch (Exception $ex) < echo $ex->getMessage(); >
Code language: HTML, XML (xml)
In this example, if an error occurs while reading the file, the execution jumps to the catch block. Therefore, the following statement will never run:
fclose($f);
Code language: PHP (php)
When the file is not closed properply, it may be inaccessible later.
To ensure that the file will be closed properly regardless of whatever exception occurs or not, you can close the file in the finally block like this:
$data = []; try < $f = fopen('data.csv', 'r'); while ($row = $fgetcsv($f)) < $data[] = $row; >> catch (Exception $ex) < echo $ex->getMessage(); > finally < if ($f) < fclose($f); >>
Code language: HTML, XML (xml)
The finally is an optional block of the try…catch statement. The finally block always executes after the try or catch block.
In this case, if an exception occurs while reading the file, the execution jumps to the catch block to handle it and then the finally block executes to close the file.
The syntax of the try. catch. finally block is as follows:
try < // do something > catch (Exception $e) < // code to handle exception > finally < // code to clean up the resource >
Code language: HTML, XML (xml)
PHP finally & return
The following defines the divide() function that returns the division of two numbers. If an error occurs, it returns null .
function divide($x, $y) < try < $result = $x / $y; return $result; > catch (Exception $e) < return null; > finally < return null; > >
Code language: HTML, XML (xml)
However, the following displays NULL instead of 5:
// . $result = divide(10, 2); var_dump($result); // NULL
Code language: HTML, XML (xml)
Typically, the return statement immediately stops the execution and returns a value. However, it doesn’t work that way when it is used with the try. catch. finally statement.
When you use the return statement with the try. catch. finally statement, the finally block still executes after the return statement.
The result will be returned after the finally block is executed. Also, if the finally block has a return statement, the value from the finally block will be returned.
The try…finally statement
In the try. catch..finally statement, either the catch or finally block is optional. Therefore, you can have the try. finally statement like this:
try < // do something > finally < // clean up >
Code language: HTML, XML (xml)
The try. finally statement allows you to throw an exception while cleaning up the resource appropriately.
Summary
- Use the try. catch. finally statement to handle exceptions and clean up the resources.
- The finally block always executes after the try or catch block.
- If the try or catch has the return statement, the value will be returned only after the finally block executes.
Исключения PHP: Try Catch для обработки ошибок
Sajal Soni Last updated Dec 20, 2021
В этом посте вы узнаете, как использовать обработку исключений в PHP. Начиная с PHP 5, мы можем использовать блоки try catch для обработки ошибок — это лучший способ обработки исключений и управления потоком вашего приложения. В этой статье мы рассмотрим основы обработки исключений вместе с несколькими примерами из реального мира.
Что такое исключение?
В PHP 5 появилась новая модель ошибок, которая позволяет вам кидать и ловить исключения в вашем приложении — это лучший способ обработки ошибок, чем то, что мы имели в более старых версиях PHP. Все исключения являются экземплярами базового класса Exception , который мы можем расширить, чтобы ввести наши собственные пользовательские исключения.
Здесь важно отметить, что обработка исключений отличается от обработки ошибок. При обработке ошибок мы можем использовать функцию set_error_handler для установки нашей настраиваемой функции обработки ошибок, чтобы всякий раз, когда срабатывает ошибка, она вызывала нашу функцию обработки ошибок. Таким образом, вы можете управлять ошибками. Однако, как правило, некоторые виды ошибок не восстанавливаются и прекращают выполнение программы.
С другой стороны, исключения — это что-то, что умышленно вызывает код, и ожидается, что он будет пойман в какой-то момент вашего приложения. Таким образом, мы можем сказать, что исключения восстанавливаются, а не определенные ошибки, которые не подлежат восстановлению. Если исключение, которое выбрасывается, попадает где-то в ваше приложение, выполнение программы продолжается с момента, когда исключение было поймано. А исключение, которое не попадает нигде в ваше приложение, приводит к ошибке, которое останавливает выполнение программы.
Поток управления обработкой исключений
Давайте рассмотрим следующую диаграмму, которая показывает общий поток управления обработкой исключений.
Исключения могут быть выброшены и пойманы с помощью блоков try и catch . Вы несете ответственность за выброс исключений, если что-то произойдет, чего не ожидается. Давайте быстро рассмотрим основной поток обработки исключений, как показано в следующем псевдокоде.
// code before the try-catch block