Zum Inhalt springen

PHP OOP Basics: Exception Handling

Exception kann wie weit verbreitet geworfen (throw) und abgefangen (catch) werden.

<?php

function divide($x, $y) {
    if(!$y) {
        throw new Exception('Teilen durch Null nicht möglich.');
    }
    return $x/$y;
}

try {
    echo divide(9,3)."\n";
    echo divide(2,0)."\n";
}
catch(Exception $e) {
    echo 'Exception abgefangen: '.$e->getMessage();
}

Was und warum finally?

try {
    throw_exception();
} catch (ExceptionTypeA $e) {
    echo $e->getMessage();
}

some_code(); // wird nicht ausgeführt wenn z.B. throw_exception ExceptionTypeB wirft
finally {
    some_code(); // Wird immer ausgeführt, auch wenn throw_exception ExceptionTypeB wirft.
}

Kommentare sind geschlossen, aber Trackbacks und Pingbacks sind möglich.