Nasıl komut ölmeden bir istisna kullanabilir?

2 Cevap

Benim kod bölümünde hata işleme için bir istisna kullanmak istiyorum ama kod başarısız olursa, ben komut dosyası devam etmek istiyorum. Ama hatayı giriş yapmak istiyorum. Birisi bana bu anlamaya yardım edebilir misiniz?


try{
    if($id == 4)
    {
      echo'test';
    }
}
catch(Exception $e){
    echo $e->getMessage();
}

echo'Hello, you should see me...'; <------ I never see this.. No errors, just a trace.

2 Cevap

may bir Exception yapmak atmak calling kod kodu

try { 
    // code that may break/throw an exception
    echo 'Foo';
    throw new Exception('Nothing in this try block beyond this line');
    echo 'I am never executed';
    throw new CustomException('Neither am I');
} catch(CustomException $e) {
    // continue here when any CustomException in try block occurs
    echo $e->getMessage();
} catch(Exception $e) { 
    // continue here when any other Exception in try block occurs
    echo $e->getMessage();
}

// script continues here
echo 'done';

Çıktı (okunabilmesi için satır sonlarını ekleme) olacak:

'Foo'                                         // echoed in try block
'Nothing in this try block beyond this line'  // echoed in Exception catch block
'done'                                        // echoed after try/catch block

Yakala / deneyin bloklar da iç içe olabilirler. Yukarıda bağlantılı PHP Manual sayfasında bakınız Örnek 2:

try{
    try {
        throw new Exception('Foo');
        echo 'not getting here';
    } catch (Exception $e) {
        echo $e->getMessage();
    }
    echo 'bar';
} catch (Exception $e) {
    echo $e->getMessage();
}
echo 'done';

'Foo'  // echoed in inner catch block
'bar'  // echoed after inner try/catch block
'done' // echoed after outer try/catch block

Dahası DevZone okuma:

Sen istisna yakalamak zorundayız:

// some code

try {
    // some code, that might throw an exception
    // Note that, when the exception is thrown, the code that's after what
    // threw it, until the end of this "try" block, will not be executed
} catch (Exception $e) {
    // deal with the exception
    // code that will be executed only when an exception is thrown
    echo $e->getMessage(); // for instance
}

// some code, that will always be executed


And here are a couple of things you should read :