php try code example

Example 1: php throw exception

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}

Example 2: try catch php

function inverso($x) {
    if (!$x) {
        throw new Exception('Zero division.');
    }
    return 1/$x;
}

try {
    echo inverso(5) . "\n";
    echo inverso(0) . "\n";
} catch (Exception $e) {
    echo 'and the error is: ',  $e->getMessage(), "\n";
}

Example 3: javascript try

var someNumber = 1;
try {
  someNumber.replace("-",""); //You can't replace a int
} catch(err) {
 console.log(err);
}

Example 4: php try catch

<?php

function test() {
    try {
        throw new Exception('foo');
    } catch (Exception $e) {
        return 'catch';
    } finally {
        return 'finally';
    }
}

echo test();
?>

Example 5: try catch php

try {
}
catch(Exception $e) {
}

Example 6: php catch exception

<?php
function inverse($x) {
    if (!$x) {
       throw new Exception('Division durch Null.');
    }
    return 1/$x;
}

try {
    echo inverse(5) . "\n";
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Exception abgefangen: ',  $e->getMessage(), "\n";
}

// Ausführung fortsetzen
echo "Hallo Welt\n";
?>

Tags:

Php Example