Author Topic: PHP - Whats the point in using try catch exceptions?  (Read 5714 times)

0 Members and 1 Guest are viewing this topic.

Offline m0l0ko

  • Peasant
  • *
  • Posts: 129
  • Cookies: -4
    • View Profile
PHP - Whats the point in using try catch exceptions?
« on: January 07, 2013, 09:51:25 am »
I encountered the concept of exception handling in a java applet I was back engineering, in that case there was no way around using those try and catch exceptions. I found out they have them in PHP so I wanna learn how to use them but I can't see how they are any different to just using if statements. For example, I'm making a web spider right now and I decided to try and make use of exceptions:

Code: [Select]
               
try {   
    @$new_input_file = file_get_contents($wiki_url);
                   
    if ($new_input_file == FALSE) {
        throw new Exception("Could not find the wiki page");
    }
                   
    else { file_put_contents($input_file_path, $new_input_file); }   
}

catch (Exception $e) { echo $e->getMessage(); }

As you can see, it tries to get content from the wiki page, if it can't and the file_get_contents function returns FALSE, then it throws a new exception. From what I read, without the @ symbol in front of the $new_file_input variable, the file_get_contents() function would return an error message rather than FALSE. 

The code works but it seems completely pointless, why wouldn't I just do:
Code: [Select]
if (@$new_input_file !== FALSE) {
    file_put_contents($input_file_path, $new_input_file);
}


SIDE QUESTION: Whats the point in using fread() to get a files contents when you can just use file_get_contents()? Are there any advantages fread()? I know that fwrite() has the advantage over file_put_contents() of being able to append strings to a file, but if you just wanna write to a file once, then I'm guessing file_put_contents() is better since.
« Last Edit: January 07, 2013, 10:00:03 am by m0l0ko »

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
Re: PHP - Whats the point in using try catch exceptions?
« Reply #1 on: January 07, 2013, 10:23:29 am »
First: I don't know PHP. But I know about the concept of exception handling.
Sometimes you really might just use an if-statement instead, that is right. But there are cases, where an exception is better.

So what is the difference to using an if-statement?

If you throw an exception, the code afterwards is not executed. That means your example doesn't need an else-block there.
Big advantage is that you can throw the exception out of your function/method and catch it in the caller of the function or throw it again. That means you handle the exception where it is useful and not immediately in the piece of code where it happens. That helps keeping your code flexible. Example: You throw an exception in your logic module, which is called by your user interface. You handle the exception in your user interface code to create a window that shows that exception instead of having to create a window (which is part of the GUI!) in your logic module. Why do you want to do that? So you can use several user interfaces/callers that handle the exception of your code differently.

That is also useful in telling the caller of your function (or someone who uses or reads your code) that he didn't use the function in the correct way or that something happend that is not supposed to happen. This context is more clear than using an obscure return type like null in Java which will probably create more errors, obscuring the real cause of that error. Especially when you create an API for others it will help them to understand what they did wrong when using your code. But it will help you too, when dealing with your own code.

You also might have several statements in your try-block that can throw exceptions. Instead of nesting if-else-statements all the way to prevent the rest of the code to be executed, you will create one try-catch block around it and the code within is more clear.

Example:
Code: [Select]
ret = compute1();
if(ret != false) {
  ret = compute2();
  if(ret != false) {
     //do something
  } else {
     print error message
  }
} else {
  print error message
}

vs:
Code: [Select]
try {
 compute1(); //throws exception to the caller
 compute2(); //throws exception to the caller
 //do something
} catch( Exception e) {
   print message of e
}
« Last Edit: January 07, 2013, 10:42:16 am by Deque »

Offline aichi

  • /dev/null
  • *
  • Posts: 8
  • Cookies: 2
  • aichi ninja
    • View Profile
    • aichi-ninja's github
Re: PHP - Whats the point in using try catch exceptions?
« Reply #2 on: March 11, 2013, 06:59:51 am »
Quote
SIDE QUESTION: Whats the point in using fread()

using file_get_contents will give you the entire contents of a file (or remote URL) into a big string. fread is handy when reading a certain length of bytes from a file, or reading data from a socket (or whatever stream)
-- silence is not a virtue
http://aichi-ninja.blogspot.com/

Offline wookie

  • Peasant
  • *
  • Posts: 68
  • Cookies: -4
    • View Profile
Re: PHP - Whats the point in using try catch exceptions?
« Reply #3 on: March 11, 2013, 09:01:11 am »
I know that fwrite() has the advantage over file_put_contents() of being able to append strings to a file, but if you just wanna write to a file once, then I'm guessing file_put_contents() is better since.


Code: [Select]
<?php


while(true){
file_put_contents("/tmp/myFile.txt""Another crap line\n"FILE_APPEND);
}


?>


[size=78%]Please run that for five minutes and then come back to me about whether you can append files with file_put_contents.[/size]

Offline Stackprotector

  • Administrator
  • Titan
  • *
  • Posts: 2515
  • Cookies: 205
    • View Profile
Re: PHP - Whats the point in using try catch exceptions?
« Reply #4 on: March 11, 2013, 09:15:50 am »
I encountered the concept of exception handling in a java applet I was back engineering, in that case there was no way around using those try and catch exceptions. I found out they have them in PHP so I wanna learn how to use them but I can't see how they are any different to just using if statements. For example, I'm making a web spider right now and I decided to try and make use of exceptions:

Code: [Select]
               
try {   
    @$new_input_file = file_get_contents($wiki_url);
                   
    if ($new_input_file == FALSE) {
        throw new Exception("Could not find the wiki page");
    }
                   
    else { file_put_contents($input_file_path, $new_input_file); }   
}

catch (Exception $e) { echo $e->getMessage(); }

As you can see, it tries to get content from the wiki page, if it can't and the file_get_contents function returns FALSE, then it throws a new exception. From what I read, without the @ symbol in front of the $new_file_input variable, the file_get_contents() function would return an error message rather than FALSE. 

The code works but it seems completely pointless, why wouldn't I just do:
Code: [Select]
if (@$new_input_file !== FALSE) {
    file_put_contents($input_file_path, $new_input_file);
}


SIDE QUESTION: Whats the point in using fread() to get a files contents when you can just use file_get_contents()? Are there any advantages fread()? I know that fwrite() has the advantage over file_put_contents() of being able to append strings to a file, but if you just wanna write to a file once, then I'm guessing file_put_contents() is better since.
biggest reason is error catching. If statements are for usual errors. And a try and catch will catch PHP errors, error who are most likely fatal (for example a wrong array index.)
~Factionwars

Offline wookie

  • Peasant
  • *
  • Posts: 68
  • Cookies: -4
    • View Profile
Re: PHP - Whats the point in using try catch exceptions?
« Reply #5 on: March 11, 2013, 10:27:27 am »
biggest reason is error catching. If statements are for usual errors. And a try and catch will catch PHP errors, error who are most likely fatal (for example a wrong array index.)


And other errors too, for the benefit of OP.


Code: [Select]
<?php


try {


if(
false) throw new CustomException("This is a test");


}catch(
CustomException $e){
error_log($e->getMessage());
}


?>


Offline aichi

  • /dev/null
  • *
  • Posts: 8
  • Cookies: 2
  • aichi ninja
    • View Profile
    • aichi-ninja's github
Re: PHP - Whats the point in using try catch exceptions?
« Reply #6 on: March 11, 2013, 05:07:16 pm »
i'm glad wookie mentioned that, here are some standard exceptions for PHP, http://www.php.net/manual/en/spl.exceptions.php
-- silence is not a virtue
http://aichi-ninja.blogspot.com/