Bird
Raised Fist0
PHPprogramming~10 mins

Multiple catch blocks in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Multiple catch blocks
Try block starts
↓
Code runs
↓
Exception thrown?
No→Try block ends normally
Yes↓
Check first catch block type
↓
Handle
↓
No matching catch
→Uncaught exception
↓
End try-catch
The try block runs code that might throw exceptions. If an exception occurs, PHP checks each catch block in order to find one matching the exception type to handle it.
Execution Sample
PHP
<?php
try {
  throw new Exception("Error!");
} catch (TypeError $e) {
  echo "Type error caught";
} catch (Exception $e) {
  echo "Exception caught";
}
?>
This code throws an Exception, which is caught by the second catch block and prints a message.
Execution Table
StepActionException Thrown?Catch Block CheckedCatch Block Matches?Output
1Enter try blockNoN/AN/A
2Throw Exception("Error!")Yes: Exceptioncatch(TypeError)No
3Check next catch blockYes: Exceptioncatch(Exception)YesException caught
4Catch block executedHandledN/AN/AException caught
5Exit try-catchHandledN/AN/AException caught
💡 Exception caught by catch(Exception), so execution continues after try-catch.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
$eundefinedException object createdException object assigned in catchException object assigned in catch
Key Moments - 2 Insights
Why doesn't the first catch block handle the Exception?
Because the first catch block is for TypeError, but the thrown exception is Exception. The execution_table row 2 shows catch(TypeError) checked and does not match.
What happens if no catch block matches the exception?
The exception remains uncaught and causes a fatal error. The concept_flow shows that if no catch matches, the exception is uncaught.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, which catch block matches the exception?
Acatch(TypeError)
Bcatch(Exception)
CNo catch block matches
DBoth catch blocks match
💡 Hint
See execution_table row 3 where catch(Exception) matches the thrown Exception.
At which step does the exception get handled?
AStep 4
BStep 3
CStep 2
DStep 5
💡 Hint
Check execution_table row 4 where catch block is executed and output is produced.
If the thrown exception was a TypeError instead, which catch block would handle it?
Acatch(Exception)
BNo catch block would handle it
Ccatch(TypeError)
DBoth catch blocks would handle it
💡 Hint
Refer to variable_tracker and execution_table row 2 where catch(TypeError) is checked first.
Concept Snapshot
try {
  // code that may throw
} catch (ExceptionType1 $e) {
  // handle ExceptionType1
} catch (ExceptionType2 $e) {
  // handle ExceptionType2
}

PHP checks catch blocks in order and runs the first matching one.
Full Transcript
This example shows how PHP handles multiple catch blocks. The try block runs code that throws an Exception. PHP checks each catch block in order. The first catch block is for TypeError, which does not match. The second catch block matches Exception, so it runs and prints 'Exception caught'. If no catch block matched, the exception would be uncaught and cause an error. Variables like $e hold the exception object inside the catch block. This flow helps handle different error types separately.

Practice

(1/5)
1.

What is the main purpose of using multiple catch blocks in PHP?

easy
A. To handle different types of exceptions separately
B. To run multiple try blocks at once
C. To catch errors without specifying the type
D. To speed up the program execution

Solution

  1. Step 1: Understand the role of catch blocks

    Catch blocks are used to handle exceptions that occur in the try block.
  2. Step 2: Recognize the benefit of multiple catch blocks

    Multiple catch blocks allow handling different exception types in different ways, improving error management.
  3. Final Answer:

    To handle different types of exceptions separately -> Option A
  4. Quick Check:

    Multiple catch blocks = different exception handling [OK]
Hint: Multiple catch blocks handle specific exceptions separately [OK]
Common Mistakes:
  • Thinking multiple catch blocks run in parallel
  • Believing catch blocks catch all errors without type
  • Assuming multiple catch blocks improve speed
2.

Which of the following is the correct syntax to catch multiple exceptions in PHP?

try {
    // code
} catch (ExceptionType1 $e) {
    // handle
} catch (ExceptionType2 $e) {
    // handle
}
easy
A. try { } catch ExceptionType1, ExceptionType2 { }
B. try { } catch (ExceptionType1 $e, ExceptionType2 $e) { }
C. try { } catch (ExceptionType1 $e) { } catch (ExceptionType2 $e) { }
D. try { } catch (ExceptionType1 $e | ExceptionType2 $e) { }

Solution

  1. Step 1: Review PHP multiple catch block syntax

    PHP uses separate catch blocks for each exception type, each with its own parentheses.
  2. Step 2: Identify the correct syntax

    try { } catch (ExceptionType1 $e) { } catch (ExceptionType2 $e) { } shows two separate catch blocks, which is the correct way to catch multiple exceptions.
  3. Final Answer:

    try { } catch (ExceptionType1 $e) { } catch (ExceptionType2 $e) { } -> Option C
  4. Quick Check:

    Separate catch blocks = correct syntax [OK]
Hint: Use separate catch blocks for each exception type [OK]
Common Mistakes:
  • Trying to catch multiple exceptions in one catch parentheses
  • Using commas or pipes inside catch parentheses incorrectly
  • Missing parentheses around exception type and variable
3.

What will be the output of the following PHP code?

try {
    throw new InvalidArgumentException("Invalid argument!");
} catch (RuntimeException $e) {
    echo "Runtime error caught";
} catch (InvalidArgumentException $e) {
    echo "Invalid argument caught";
}
medium
A. Invalid argument caught
B. Runtime error caught
C. No output, exception not caught
D. Fatal error

Solution

  1. Step 1: Identify the thrown exception type

    The code throws an InvalidArgumentException.
  2. Step 2: Match the thrown exception with catch blocks

    The first catch block is for RuntimeException, which does not match. The second catch block matches InvalidArgumentException, so it runs.
  3. Final Answer:

    Invalid argument caught -> Option A
  4. Quick Check:

    Exception type matches second catch block [OK]
Hint: Exception matches first compatible catch block [OK]
Common Mistakes:
  • Assuming first catch block always runs
  • Confusing exception types
  • Expecting no output if first catch fails
4.

Find the error in this PHP code snippet:

try {
    // some code
} catch (Exception $e) {
    echo "General exception";
} catch (InvalidArgumentException $e) {
    echo "Invalid argument";
}
medium
A. Missing semicolon after catch blocks
B. Try block is empty, causing syntax error
C. InvalidArgumentException cannot be caught separately
D. The catch blocks are in wrong order; specific exceptions must come first

Solution

  1. Step 1: Understand catch block order importance

    More specific exceptions must be caught before more general ones to avoid unreachable code.
  2. Step 2: Identify the order problem

    The general Exception catch block is first, so the InvalidArgumentException catch block is unreachable and causes an error.
  3. Final Answer:

    The catch blocks are in wrong order; specific exceptions must come first -> Option D
  4. Quick Check:

    Specific catch before general catch [OK]
Hint: Place specific catch blocks before general ones [OK]
Common Mistakes:
  • Putting general catch before specific catch
  • Ignoring unreachable catch block warnings
  • Assuming order does not matter
5.

Consider this PHP code:

try {
    if (rand(0,1)) {
        throw new RuntimeException("Runtime issue");
    } else {
        throw new InvalidArgumentException("Invalid argument");
    }
} catch (InvalidArgumentException | RuntimeException $e) {
    echo "Caught: " . $e->getMessage();
} catch (Exception $e) {
    echo "General exception";
}

What will this code output?

hard
A. No output
B. Caught: Runtime issue or Caught: Invalid argument
C. Syntax error due to multiple exceptions in one catch
D. General exception

Solution

  1. Step 1: Understand combined catch block syntax

    PHP 7.1+ allows catching multiple exceptions in one catch using the pipe (|) symbol.
  2. Step 2: Analyze thrown exceptions and matching catch

    Either RuntimeException or InvalidArgumentException is thrown randomly. Both are caught by the combined catch block, which prints the message.
  3. Step 3: Confirm no syntax error

    The combined catch syntax is valid, so no syntax error occurs.
  4. Final Answer:

    Caught: Runtime issue or Caught: Invalid argument -> Option B
  5. Quick Check:

    Combined catch handles both exceptions [OK]
Hint: Use | to catch multiple exceptions in one block [OK]
Common Mistakes:
  • Thinking multiple exceptions in one catch cause syntax error
  • Expecting general exception catch to run first
  • Ignoring random exception thrown
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard