Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

Palavra-chave try

Envolve operações com pelo menos um bloco catch ou finally.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

try { process(); } catch (Throwable $e) { recover($e); }

Envolve operações com pelo menos um bloco catch ou finally. Se uma operação lançar uma exceção, o restante try é ignorado e o primeiro catch compatível executa-se. Sem catch compatível a exceção propaga-se após o finally associado.

$steps=[]; try {$steps[]="start";throw new RuntimeException();$steps[]="end";}catch(RuntimeException){$steps[]="caught";}finally{$steps[]="cleanup";} echo json_encode($steps);
["start","caught","cleanup"]

Exemplos

<?php
$steps=[]; try {$steps[]="start";throw new RuntimeException();$steps[]="end";}catch(RuntimeException){$steps[]="caught";}finally{$steps[]="cleanup";} echo json_encode($steps);

Resultado

["start","caught","cleanup"]

Fontes