Try and catch php mysql

try… catch VS if…else. Что, когда и почему?

Эволюция языков программирования приводит иногда к кардинальным изменениям в мировоззрении разработчиков. В мире РНР такое случилось при появлении пятой ветки, которая принесла новую объектную модель, новые наборы встроенных функций и новые методы обработки ошибок…

Те, кто начинал знакомиться с PHP (тут и далее я буду подразумевать пятую версию), после другого процедурного языка программирования, так и не поняли что же такого в переходе от 4ки к 5ке и продолжают оформлять код привычными функциями, которые находятся на одном уровне по отношению друг к другу, а так же каждое действие проверяют на удачный код возврата. Но те кто знали об исключениях и классах…

Теория

Исключение (Exception) — сигнал отправляемый программой в интерпретатор, о возникновении нештатной (исключительной) ситуации во время исполнения кода.

В PHP работа с исключениями основана на тех же принципах что и везде. Для генерации исключения используется оператор throw, которому передается объект исключения, принимающий в конструкторе два необязательных параметра: сообщение исключения и код исключения.

Читайте также:  Map contains value in java

Для того, что бы отловить исключение, используется конструкция try. catch. В блоке try выполняются операции, которые могут привести к исключительной ситуации, а блок catch позволяет принять решение что делать, если исключение было брошено.

try throw new Exception(\\\»Exception message\\\»);
echo \\\»That code will never been executed\\\»;
> catch (Exception $e) echo $e->getMessage(); //выведет \\\»Exception message\\\»
>

Как видно из примера, при выбрасывании исключения, остальной код в блоке try выполнен не будет, а управление будет передано в оператор catch, в котором мы указываем, как будет называться объект, в который будет передано выброшенное исключение (в нашем случае — $e). Внутри блока оператора catch, на основании данных из исключения мы можем применять какое-либо действие в зависимости от ситуации. Сейчас мы просто вывели сообщение, которое было передано исключением.

Объект Exception (который кстати можно унаследовать) имеет следующий набор финальных (final) методов:

final function getMessage(); // сообщение исключения
final function getCode(); // код исключения
final function getFile(); // файл из которого брошено исключение
final function getLine(); // строка бросания
final function getTrace(); // массив стека вызовов
final function getTraceAsString(); // массив стека вызовов отформатированый в строку

Практика

Когда же удобно использовать исключения? Да всегда, когда функция или метод может прийти к ошибочной ситуации! На примере встроенной функции mysql_connect() и mysql_select_db(), если бы они бросала исключения при ошибке соединения и выборе базы данных соответственно, код выглядел бы так:
try mysql_connect($hostname, $username, $password);
mysql_select_db($dbname);
> catch (Exception $e) echo $e->getMessage(); //выведет либо сообщение об ошибке подключения, либо об ошибке выбора
>

И в зависимости от результата мы бы:

* удачно присоединились бы к СУБД и выбрали БД (код в сatch блоке не выполнился бы)
* при неудаче соединения с СУБД, вывели бы соответствующую ошибку и прикатили выполнение сеанса
* при ошибке выбора БД, оповестили бы пользователя об этой неприятности

Теперь самое время спросить: \\\«А зачем нам такая сложная штука, если можно использовать оператор if?\\\».

Первый же ответ: \\\«Потому что так код более читабельный, а обработка ошибок выведена в отдельный блок\\\». Если бы мы использовали оператор if, то код выглядел бы следующим образом:

$connId = mysql_connect($hostname, $username, $password);
if (false == $connId) echo \\\»Ошибка подключения к СУБД\\\»;
>

$flag = mysql_select_db($dbname);
if (false == $flag) echo \\\»Невозможно выбрать базу данных.\\\»;
>

Согласитесь, что в предыдущем варианте код выглядит более понятным. Но это еще не все. Теперь обработкой этих ошибок заниматься непосредственно разработчику не обязательно — достаточно выбросить исключение, а его обработкой можно заняться на более высоком уровне. Так же исключения можно передавать цепочкой (chain) наверх:

class MyException extends Exception <>

try try //.
throw new Exception(\\\»inner\\\»);
//.
> catch (Exception $e) throw new MyException(\\\»outer\\\»);
>
> catch (MyException $e) echo $e->getMessage(); //выведет \\\»outer\\\»
>

Производительность

Пытаясь достичь истины, провел несколько экспериментов с различными типами функций.
Первый тип возвращал статус true и проверялся операторами if. else
Второй тип возвращал статус false и проверялся операторами if. else
Третий тип просто выполнял действия и ничего не возвращал. Проверялся блоком try. catch
Четвертый тип всегда бросал исключение и проверялся в try. catch

True: 0.72382092475891
False: 0.85190796852112
No exception: 0.72565317153931
Exception: 14.176206827164

как и ожидалось — бросание исключений довольно накладная операция, а вот оба варианта удачного выполнения прошли тесты вровень.
Тесты проводились на примитивных функциях сложения, но в 1кк итераций

Выводы

Когда же использовать исключения? Всегда, когда подразумевается ошибка или нестандартное поведение программы, а так же когда принятие решения об обработке результата необходимо переложить на более высокий уровень.
А что же делать с оператором if и булевыми статусами отработки функций? Оставить их. Но толко там где они действительно необходимы. Тоесть там, где логический оператор подразумевает использование результата в вычислениях, а не контроле потока выполнения. Тоесть все удачные завершения функций теперь не нужно оповещать оператором return true, если это логическое значение не пригодиться для дальнейших вычислений. И в то же время все статусы завершения функций с ошибками изменить из формата return false в формат throw new Exception()
Что нужно помнить? Использование исключений предполагает что весь код выполняется со статусом true (без ошибок), но если ошибка произошла, то для ее обработки всегда найдется место в блоке catch.

Источник

Try Catch in PHP for Complex Problems

Try Catch in PHP for Understanding the Skills for Complex Problems

Hypertext Preprocessor ”PHP”, is an open source programming language that is free to download and use. It is an extensively used language and PHP programs are run on the server.

PHP Error Handling Keywords

An error is an unanticipated program result that the program cannot handle. Errors are fixed by reinstalling the application. An infinite loop that never stops executing is an example of an error.

Here’s How to Land a Top Software Developer Job

What Is an Exception?

An exception is an unexpected software result that the program can manage. Attempting to open a file that does not exist is an example of an exception. This error can be handled by either generating the file or giving the user the option of searching for it.

Exception handling is a feature of PHP try and catch blocks, which contain the code to handle exceptions. They are crucial in the management of exceptions.

Why Handle Exceptions?

  • Exceptions avoid having unexpected results on our site, which can be quite annoying to our visitors.
  • To improve the security of our applications by avoiding disclosing information that could be used by hostile users to harm them.
  • If a program’s usual flow is disrupted by a predictable error, PHP exceptions are employed.

PHP Error Handling Keywords

Try catch: The try catch in PHP that may include an exception is contained in the try block.

Throw : The throw keyword is another crucial keyword in the try-catch block. Throw is a keyword that causes an exception to be thrown.

PHP Try Catch With Multiple Exception Types

The try catch in PHP that may include an exception is contained in the try block. The catch block catches an exception raised in the try block during runtime. As a result, at least one catch block is required for each try block. It is made up of the code block where an exception can arise. The following points concerning the attempt should be noted:

  • A catch or finally block must come after the try block.
  • With one attempt block, there can be numerous catch blocks.

Catch

The try catch in PHP block raises an exception, which is caught in the catch. When a certain exception is thrown, the catch block is called. PHP looks for the catch block that matches the exception object, and assigns it to a variable.

The following are a few things to keep in mind about the catch:

  • With a try, there can be many catch blocks.
  • One or more catches catch the thrown exception and resolve it.
  • With a try block, the catch block is always used. It can’t be utilized on its own.
  • It appears immediately after the attempt block.

Use of Try Catch- Finally

Try catch in PHP is a block that contains the program’s vital code for execution. In PHP, the finally block is also used to clean up the code. The only difference is that it always runs regardless of whether or not an exception is thrown.

Kickstart Your UI/UX Career Right Here!

When to Use Try Catch-Finally

Use of Try catch-finally is useful in the following situations: database connection closure and stream.

Example

//user-defined function with an exception

//trigger an exception in a «try» block

throw new Exception(«Passed number is an ODD Number»);

echo «After throw this statement will not execute»;

echo ‘
If you see this text, the passed value is an EVEN Number ‘;

echo ‘
Exception Message: ‘ .$e->getMessage() .’‘;

echo ‘
It is finally block, which always executes.’;

echo ‘Output for ODD Number’;

echo ‘Output for EVEN Number’;

Output

Try_Catch_in_PHP

Creating Custom PHP Exception Types

  • Apart from PHP exception class and its subclasses, we can also create our own custom exception classes to handle try catch in PHP exceptions.
  • With PHP 5.5 and above, finally block is used to handle exceptions. This block is always executed anyway, whether an exception is thrown or not.

Here’s How to Land a Top Software Developer Job

How to Properly Log Exceptions in Your PHP Try Catch Blocks

Try catch in PHP introduces a new error model that allows you to throw and catch exceptions in your application, which is a far better way of dealing with mistakes than previous PHP versions. All exceptions are instances of the Exception base class, which we can modify to add our own custom exceptions.

It is vital to realize that exception handling and error handling are not the same thing. You will be able to control faults in this manner. However, some faults are unrecoverable and cause the software to stop working.

Exceptions, on the other hand, are intentionally thrown by the code and are meant to be detected at some point in your application. As a result, we can claim that exceptions are recoverable, whereas certain errors are not. If a thrown exception is caught someplace in your application, program execution resumes from where the exception was caught. And an exception that isn’t caught anywhere in your application causes an error, which stops the program from running.

How to Use Try Catch With MySQL

To begin, it’s important to note that though MySQL doesn’t have classic try catch in PHP statements, it does provide conditions, which are similar to Exceptions. Both a code and a description are included in conditions.

You basically add a handler to your procedure instead of enclosing all of your code in a try catch block. In most cases, you’ll wish to quit execution, which is handled by an exit handler in MySQL. When the handler is called, you may want to rollback or log the event, depending on the use case.

Conclusion

This is all you need to know about the concept of try catch in PHP. If you want to learn more about the same or any other topic related to web development, programming or coding, you can enroll in Simplilearn’s Full Stack Web Development program and seek expertise in your subject to advance in your career and land better job opportunities.

Besides the varied specialization courses we provide, you can also sign up on SkillUp platform, a Simplilearn initiative where we offer numerous free online courses

Find our Post Graduate Program in Full Stack Web Development Online Bootcamp in top cities:

Name Date Place
Post Graduate Program in Full Stack Web Development Cohort starts on 15th Aug 2023,
Weekend batch
Your City View Details
Post Graduate Program in Full Stack Web Development Cohort starts on 12th Sep 2023,
Weekend batch
Your City View Details
Post Graduate Program in Full Stack Web Development Cohort starts on 10th Oct 2023,
Weekend batch
Your City View Details

About the Author

Simplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

Post Graduate Program in Full Stack Web Development

Источник

Оцените статью