0
0
PHPprogramming~10 mins

Try-catch execution flow in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Try-catch execution flow
Start
Try block
Exception?
NoContinue after try
Yes
Catch block
Continue after catch
End
The program tries to run code inside the try block. If an error happens, it jumps to the catch block. Then it continues after the catch.
Execution Sample
PHP
<?php
try {
  echo "Start\n";
  throw new Exception("Error happened");
  echo "End\n";
} catch (Exception $e) {
  echo "Caught: " . $e->getMessage() . "\n";
}
?>
This code prints 'Start', then throws an error, jumps to catch, and prints the error message.
Execution Table
StepActionEvaluationOutput
1Enter try blockNo exception yetStart
2Throw ExceptionException thrown
3Jump to catch blockCatch ExceptionCaught: Error happened
4End programNo more code
💡 Exception thrown at step 2, caught at step 3, program ends normally
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
$e (Exception)nullnullException object createdException object caughtException object caught
Key Moments - 2 Insights
Why does the code after 'throw' inside try not run?
Because at step 2 in the execution_table, the exception is thrown immediately, so the program jumps to the catch block and skips the remaining try code.
What happens if no exception is thrown in try?
The program runs all try code and skips the catch block, continuing after try normally, as shown by the 'No exception yet' evaluation in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at step 1?
ACaught: Error happened
BStart
CEnd
DNothing
💡 Hint
Check the Output column at step 1 in execution_table
At which step does the program jump to the catch block?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the Action and Evaluation columns in execution_table rows
If the 'throw' line is removed, what changes in the execution_table?
AStep 2 will not throw exception and step 3 catch block will be skipped
BStep 3 will still run catch block
COutput at step 1 changes
DProgram will crash
💡 Hint
Refer to key_moments about what happens if no exception is thrown
Concept Snapshot
try {
  // code that might fail
} catch (Exception $e) {
  // code to handle error
}

- Code in try runs first
- If error (exception) happens, jump to catch
- Catch gets error info in $e
- After catch, program continues normally
Full Transcript
This example shows how PHP handles errors using try and catch. The program starts by running code inside the try block. When it reaches the throw statement, it creates an error and immediately stops running the try block. Instead, it jumps to the catch block where the error is caught and handled. The catch block prints the error message. After that, the program continues normally. If no error happens, the catch block is skipped. This flow helps programs handle problems without crashing.