Skip to main content

try catch

May 7, 2010 by ita

ita's picture

ada yg pernah nyoba fungsi seperti try catch ga? ada ga di ci?

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

BLS:

May 7, 2010 by syabac, 1 year 39 weeks ago
Comment: 6829

syabac's picture

Pernah..
Karena CI dibuat untuk bisa backward compatible dengan PHP 4.3+ maka library native CI tidak menggunakan throw/catch error.

try/catch/finally hanya ada di PHP 5+.

tapi kita bisa saja menggunakan fitur tersebut di dalam aplikasi yg berbasis CI, tentunya aplikasi yg kita buat running on top PHP 5.

contoh implementasinya misal kita mau validasi parameter yg diterima di suatu library/fungsi.

class InvalidArgumentException extends Exception {}
class DivideByZeroException extends Exception {}
 
class Mathlib{
    const OPT_ADD = 1;
    const OPT_SUB = 2;
    const OPT_MUL = 3;
    const OPT_DIV = 4;
 
    public function calc($a, $b, $operation){
        if(! is_int($a))
            throw new InvalidArgumentException('Invalid parameter given! $a must be integer.');
        if(! is_int($b))
            throw new InvalidArgumentException('Invalid parameter given! $b must be integer.');
 
        switch($operation){
            case Mathlib::OPT_ADD: return $a + $b;
            case Mathlib::OPT_SUB: return $a - $b;
            case Mathlib::OPT_MUL: return $a * $b;
            case Mathlib::OPT_DIV:
                if($b == 0)
                    throw new DivideByZeroException('Divide by zero. $b cannot be zero!');
                return $a / $b;
            default: throw new InvalidArgumentException('$opt is not valid!');
        }
    }
}
 
class Math extends Controller{
    function calc(){
        $this->load->library('Mathlib');
 
        // Variabel.
        $x = 10; $y = 7; $opt = Mathlib::OPT_ADD;
 
        try{
            $result = $this->mathlib->calc($x, $y, $opt);
            echo $result;
        }catch(InvalidArgumentException $e){
            // Do some exception handler for invalid argument exception
            echo $e->getMessage();
        }catch(DivideByZeroException $e){
            // Do some exception handler for divide by zero exception
            echo $e->getMessage();
        }catch(Exception $e){
            // Do some exception handler for general exception
            echo $e->getMessage();
        }
    }
}

semoga membantu..

fungsi catch

May 7, 2010 by andry, 1 year 39 weeks ago
Comment: 6828

andry's picture

bisa kok coba deh ...

try {
set_error_handler(create_function('', "throw new Exception(); return true;"));
// put your code here
} catch(Exception $e) {
// hande the exception
}

Premium Drupal Themes by Adaptivethemes