Website Development Prices

Search Blog

Monday, May 30, 2016

Rukovanje greskama koje se dese u funkciji (Handling errors that occur in the function)

Ako se u funkciji desi neka greska, ona cesto namerno vraca false. Ne samo da su mnoge ugradjene PHP funkcije napravljene na ovaj nacin, vec treba da radite isto i kad pisete svoje funkcije. 

Primer: izracunavanje reciprocne vrednosti. Funkcija vraca netacno (FALSE), ako se trazi reciprocna vrednost sa 0.

function reciprocna_vrednost($vrednost)
{
if($vrednost != 0){
return 1 / $vrednost;
}
else {
return FALSE;
}

}


Jedan od nacina da se rukuje greskom koja je naznacena vracanjem vrednosti FALSE iz funkcije, je da se koristi funkcija die iz PHP-a, koja je ista kao i funkcija exit. Ovoj funkciji prosledjujete poruku i ona zavrsava skript, pri cemu se prikazuje ta poruka.

Primer 2: funkcija fopen otvara fajlove (OOP i rukovanje fajlovima). Ako funkcija ne moze da otvori fajl, sto je slucaj kada fajl ne moze da se pronadje, funkcija vraca vrednost FALSE. U tom slucaju biste mogli da pomocu PHP operatora pokusate da otvorite fajl ili da zavrsite program, ako ne moze da se otvori.

<?php

$imeFajla = "fajl_ne_postoji";
$fajl = fopen($imeFajla, "r")

or die("Fajl $imeFajla se ne moze otvoriti. Nije pronadjen.");

?>


Objasnjenje: ako pokusate da otvorite fajl koji ne postoji dobicete sledecu poruku, koju cine poruka upozorenja (Warning) od PHP-a i tekst koji ste poslali funkciji die.

Rezultat:




If in a function some kind of error happens , it often deliberately returns false. Not only that are many built-in PHP function made in this way, but you should do the same when you write your functions.

Example: calculation of reciprocal value. The function returns false (FALSE), if requested reciprocal value with 0.

function reciprocal_value($value)
{
if($value != 0){
return 1 / $value;
}
else {
return FALSE;
}

}

One way of handling error that is indicated with the return of value FALSE in function, is die - the function of PHP, which is the same as the function exit. To this function you forward the message and it ends script, which displays the message.

Example 2: fopen opens files (OOP and handling files). If a function can not open the file, which is the case when a file can not be found, the function returns FALSE. In this case you can use PHP operators to try to open the file or to terminate the program if it can not be opened.

<?php

$fileName = "file_does_not_exist";
$file = fopen($fileName, "r")
or die("File $fileName can not be opened. Not found.");


?>

Explanation: if you try to open a file that does not exist, you will get the following message, which consists of an warning  (Warning) message from PHP and text that you sent to the function die.


Result:




No comments:

Post a Comment

Note: Only a member of this blog may post a comment.