PHP Exceptions

What is an Exception? #

Үл хамаарах зүйл гэж юу вэ? #

An exception is an object that describes an error or unexpected behaviour of a PHP script.

PHP скриптийн алдаа эсвэл гэнэтийн зан үйлийг дүрсэлсэн объект нь үл хамаарах зүйл юм.

Exceptions are thrown by many PHP functions and classes.

Үл хамаарах зүйлийг олон PHP функцууд болон ангиуд хаядаг.

User defined functions and classes can also throw exceptions.

Хэрэглэгчийн тодорхойлсон функц, ангиуд нь үл хамаарах зүйлүүдийг бас хаях боломжтой.

Exceptions are a good way to stop a function when it comes across data that it cannot use.

Үл хамаарах зүйл нь функцийг ашиглах боломжгүй өгөгдөлтэй тулгарахад зогсоох сайн арга юм.


Throwing an Exception #

Үл хамаарах зүйл хаях #

The throw statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed.

throw мэдэгдэл нь хэрэглэгчийн тодорхойлсон функц эсвэл аргад үл хамаарах зүйлийг хаях боломжийг олгодог. Онцгой тохиолдол гарсан тохиолдолд түүнийг дагаж мөрдөх код биелэгдэхгүй.

If an exception is not caught, a fatal error will occur with an “Uncaught Exception” message.

Хэрэв үл хамаарах зүйл баригдахгүй бол “Uncaught Exception” гэсэн мессеж гарч ирэхэд ноцтой алдаа гарна.

Lets try to throw an exception without catching it:

Онцгой тохиолдлыг барьж авалгүйгээр хаяхыг хичээе.

Example #

Жишээ #

<?php function divide($dividend, $divisor) { if($divisor == 0) { throw new Exception("Division by zero"); } return $dividend / $divisor; } echo divide(5, 0); ?>

The result will look something like this:

Үр дүн нь иймэрхүү харагдах болно:

Fatal errorUncaught Exception: Division by zero in C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 {main} thrown in C:\webfolder\test.php on line 4

The try…catch Statement #

Туршилт … барих мэдэгдэл #

To avoid the error from the example above, we can use the try...catch statement to catch exceptions and continue the process.

Дээрх жишээнээс гарах алдаанаас зайлсхийхийн тулд бид try...catch мэдэгдэлийг ашиглан үл хамаарах зүйлүүдийг олж, үйл явцыг үргэлжлүүлж болно.

Syntax #

try {
  code that can throw exceptions
catch(Exception $e) {
  code that runs when an exception is caught
}

Example #

Жишээ #

Show a message when an exception is thrown:

Онцгой тохиолдол гарсан тохиолдолд зурвас харуулах:

<?php function divide($dividend, $divisor) { if($divisor == 0) { throw new Exception("Division by zero"); } return $dividend / $divisor; } try { echo divide(5, 0); } catch(Exception $e) { echo "Unable to divide."; } ?>

The catch block indicates what type of exception should be caught and the name of the variable which can be used to access the exception. In the example above, the type of exception is Exception and the variable name is $e.

Баригдах блок нь ямар төрлийн онцгой тохиолдлыг барих ёстой, үл хамаарах зүйлд нэвтрэхэд ашиглаж болох хувьсагчийн нэрийг заана. Дээрх жишээнд үл хамаарах зүйл нь Exception бөгөөд хувьсагчийн нэр нь $e.


The try…catch…finally Statement #

The try...catch...finally statement can be used to catch exceptions. Code in the finally block will always run regardless of whether an exception was caught. If finally is present, the catch block is optional.

try...catch...finally  мэдэгдэл нь үл хамаарах зүйлүүдийг ашиглаж болно. finally блок дахь код нь онцгой тохиолдол гарсан эсэхээс үл хамааран үргэлж ажиллана. Хэрэв finally  байгаа бол catch блок нь заавал байх албагүй.

Syntax #

try {
  code that can throw exceptions
catch(Exception $e) {
  code that runs when an exception is caught
finally {
  code that always runs regardless of whether an exception was caught
}

Example #

Жишээ #

Show a message when an exception is thrown and then indicate that the process has ended:

Үл хамаарах зүйл гарах үед мессежийг харуулаад дараа нь процесс дууссаныг харуулна уу:

<?php function divide($dividend, $divisor) { if($divisor == 0) { throw new Exception("Division by zero"); } return $dividend / $divisor; } try { echo divide(5, 0); } catch(Exception $e) { echo "Unable to divide. "; } finally { echo "Process complete."; } ?>

Example #

Жишээ #

Output a string even if an exception was not caught:

Онцгой тохиолдол гараагүй ч гэсэн давхардсаныг гаргана уу:

<?php function divide($dividend, $divisor) { if($divisor == 0) { throw new Exception("Division by zero"); } return $dividend / $divisor; } try { echo divide(5, 0); } finally { echo "Process complete."; } ?>

The Exception Object #

The Exception Object contains information about the error or unexpected behaviour that the function encountered.

Exception Object нь тухайн функцэд гарсан алдаа эсвэл гэнэтийн зан үйлийн талаархи мэдээллийг агуулдаг.

Syntax #

new Exception(message, code, previous)

шинэ онцгой тохиолдол (мессеж, код, өмнөх)

Parameter Values #

Parameter Description
message Optional. A string describing why the exception was thrown

Нэмэлт. Үл хамаарах зүйлийг яагаад хаясныг тайлбарласан үг

code Optional. An integer that can be used used to easily distinguish this exception from others of the same type

Нэмэлт. Энэ үл хамаарлыг ижил төрлийн бусад хүмүүсээс амархан ялгахад ашиглаж болох бүхэл тоо

previous Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter

Нэмэлт. Хэрэв энэ онцгой тохиолдлыг өөр нэг үл хамаарах зүйлийн блокт хаясан бол энэ үл хамаарлыг энэ параметрт шилжүүлэхийг зөвлөж байна

Methods #

When catching an exception, the following table shows some of the methods that can be used to get information about the exception:

Үл хамаарах зүйлийг авахдаа дараахь хүснэгтэд үл хамаарах зүйлийн талаар мэдээлэл авахад ашиглаж болох зарим аргыг харуулав:

Method Description
getMessage() Returns a string describing why the exception was thrown

Үл хамаарах зүйлийг яагаад хаясныг тайлбарласан мөрийг буцаана

getPrevious()

If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null

Хэрэв энэ онцгой тохиолдлыг өөр нэг нь өдөөсөн бол энэ арга нь өмнөх онцгой тохиолдлыг буцаана. Хэрэв үгүй ​​бол тэг болно

getCode() Returns the exception code

Үл хамаарах кодыг буцаана

getFile() Returns the full path of the file in which the exception was thrown

Үл хамаарах зүйлийг хаясан файлын бүтэн замыг буцаана

getLine() Returns the line number of the line of code which threw the exception

Үл хамаарах зүйлийг оруулсан кодын мөрийн мөрийн дугаарыг буцаана

Example #

Жишээ #

Output information about an exception that was thrown:

Шилжүүлсэн үл хамаарах зүйлийн талаархи мэдээлэл:

<?php function divide($dividend, $divisor) { if($divisor == 0) { throw new Exception("Division by zero", 1); } return $dividend / $divisor; } try { echo divide(5, 0); } catch(Exception $ex) { $code = $ex->getCode(); $message = $ex->getMessage(); $file = $ex->getFile(); $line = $ex->getLine(); echo "Exception thrown in $file on line $line: [Code $code] $message"; } ?>

Complete Exception Reference #

For a complete reference, go to our Complete PHP Exception Reference.

Бүрэн лавлагаа авахын тулд манай PHP-ийн бүрэн бус онцгой тохиолдлын лавлагаа руу орно уу.

The reference contains descriptions and examples of all Exception methods.

Лавлагаа нь бүх онцгой тохиолдлын аргуудын тайлбар, жишээг агуулдаг.

Powered by BetterDocs

Leave a Reply