www.webdeveloper.com
Results 1 to 6 of 6

Thread: try catch with list() and explode()

  1. #1
    Join Date
    Dec 2010
    Location
    Brazil
    Posts
    32

    try catch with list() and explode()

    Given this code?

    Code:
    $data = array('08/23'); // Note that there is no yyyy, only mm/dd.
    list($dia, $mes, $ano) = explode('/', $data);
    How can I use a try catch to avoid breaking my application in case
    explode() finds only two (or even one) piece? I ask because simply doing

    Code:
    try {
        list($dia, $mes, $ano) = explode('/', $data);
    }
    catch (Exception $e) {
        // ...
    }
    I cannot catch the exception. Why?

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,334
    It's not an exception (it's an error).

    You can either change the error reporting level, or (my choice) just add a bit of defensive coding:
    PHP Code:
    $data '08/23/2013'// I assume this should have been a string, not array?
    $parts explode('/'$data);
    if(
    count($parts) >= 3) {
        list(
    $dia$mes$ano) = $parts;
    }
    else {
        
    // handle error here

    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    Dec 2010
    Location
    Brazil
    Posts
    32
    Quote Originally Posted by NogDog View Post
    It's not an exception (it's an error).
    Can't I use try catch to prevent errors from breaking the applicaton?

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,334
    Possibly, if you use set_error_handler() and code it to throw exceptions on those types of errors (if it allows you to -- it does not support all error types).
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  5. #5
    Join Date
    Dec 2010
    Location
    Brazil
    Posts
    32
    Okay, so, now I see that somethings do now cause/throw exceptions. That is
    clear. But then, I realized that I don't understand the difference (or advantage)
    between simply using plain conditionals to check for stuff or using try/catch
    blocks. In my case I would have to do:

    Code:
    if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    
        $data = $_POST['data'];
        $data_arr = explode('/', $data);
    
        try {
            if (sizeof($data_arr) != 3)
                throw new Exception('Formato da data possivelmente inválido.');
            else {
                list($mes, $dia, $ano) = $data_arr;
    
                if (checkdate($mes, $dia, $ano))
                    echo '<p>', $data, ' - Data Válida!</p>';
                else
                    echo '<p>', $data, ' - Data inválida...</p>';
            }
        }
        catch (Exception $e) {
            echo '<p>', $e->getMessage(), '.</p>';
        }
    }
    Why not just use if/else and forget about the try/catch?

  6. #6
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,334
    Generally, an exception represents some "exceptional" state of the program's execution that in theory should not happen in "normal" usage, but which is not impossible, so you want to catch it when it happens and handle it is some way other than just letting everything blow up in the user's face. Since users making invalid inputs is not particularly exceptional, I personally probably would not try to handle them via exceptions. But if you like throwing/catching exceptions as a mechanism for that, then your approach could work. If you go that route, you might want to extend the Exception class so that you can catch them and treat them differently from other, more exceptional exceptions.
    PHP Code:
    class InputException extends Exception {}

    try {
        if(!
    is_numeric($_POST['some_number'])) {
            throw new 
    InputException($e);
        }
    }
    catch(
    InputException $e) {
        
    // handle user input exceptions here
    }
    catch(
    Exception $e) {
        
    // handle other exceptions here

    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles