100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
PHP

Exceptions and Error Handling

Learn how PHP represents runtime failures as throwable objects, how try/catch/finally blocks control the flow around them, and how to design a clean exception hierarchy for your application.

Error Handling & NamespacesIntermediate10 min readJul 9, 2026
Analogies

Exceptions and Error Handling

PHP treats most runtime failures as objects that implement the Throwable interface, rather than as return codes or silent warnings. When something goes wrong — a database connection drops, a required array key is missing, a file cannot be opened — code can throw an exception object that carries a message, a numeric code, and (crucially) the exact call stack at the moment of failure. Surrounding code can catch that object, inspect it, recover, log it, or let it propagate upward until something knows how to handle it. This model separates the 'happy path' of your business logic from the 'what if it fails' branches, which keeps functions readable and makes failure handling explicit rather than scattered through if-checks on return values.

🏏

Cricket analogy: When a batter gets a controversial LBW decision, the umpire doesn't just wave play on silently — he raises a decision object with a reason, letting the third umpire 'catch' it for review before it's accepted or overturned.

The Throwable hierarchy: Error vs Exception

Since PHP 7, both Error and Exception implement the Throwable interface, so a single catch block can intercept either if it type-hints Throwable. Error and its subclasses (TypeError, DivisionByZeroError, ArgumentCountError) represent internal engine failures — calling a function with the wrong argument types, dividing by zero, or invoking a method on null. Exception and its subclasses (InvalidArgumentException, RuntimeException, LogicException) represent application-level failures you throw deliberately. Catching Error is possible but should be rare and deliberate; most of the time you want your own code to raise typed Exception subclasses that describe a specific failure mode, and let genuine engine errors surface during development instead of being silently swallowed.

🏏

Cricket analogy: A no-ball called for overstepping is like an Error — the game's own engine flagged a rule violation — while a batter deliberately retiring hurt is like an Exception, a choice made within the normal flow for a specific reason.

php
<?php
declare(strict_types=1);

final class InsufficientFundsException extends RuntimeException
{
    public function __construct(
        public readonly float $requested,
        public readonly float $available,
    ) {
        parent::__construct(
            sprintf('Requested %.2f but only %.2f available', $requested, $available)
        );
    }
}

final class Account
{
    public function __construct(private float $balance) {}

    public function withdraw(float $amount): void
    {
        if ($amount > $this->balance) {
            throw new InsufficientFundsException($amount, $this->balance);
        }
        $this->balance -= $amount;
    }
}

$account = new Account(50.00);

try {
    $account->withdraw(75.00);
} catch (InsufficientFundsException $e) {
    echo "Denied: {$e->getMessage()}\n";
    echo "Short by " . ($e->requested - $e->available) . "\n";
} finally {
    echo "Withdrawal attempt logged.\n";
}

try, catch, finally and multi-catch

A try block wraps code that might throw. One or more catch blocks follow, each matching a specific Throwable type (or a union of types separated by pipes, e.g. catch (TypeError | ValueError $e)). PHP checks catch blocks in order and runs the first one whose type matches, so list more specific exception types before their parent classes. The optional finally block always executes — whether the try succeeded, an exception was caught, or an exception was never caught at all and is about to propagate — making it the right place to release resources like file handles or database connections regardless of outcome.

🏏

Cricket analogy: A team's rain-delay protocol tries to continue play, has ordered responses from 'light drizzle' to 'washout,' and always runs the ground-covering procedure afterward regardless of which scenario occurred, protecting the pitch either way.

Think of an exception as a package thrown up a staircase. Each catch block on the way up gets to look at the label and decide whether to open it (handle it) or let it keep flying to the next landing. finally is the doorman at every landing who always does his job — checking coats, closing doors — no matter what happens to the package.

Custom exception hierarchies and rethrowing

Well-designed applications define their own exception classes that extend built-in ones like RuntimeException (failures detectable only at runtime) or LogicException (programmer errors that should never happen if the code is correct, like calling a method before initialization). Grouping related exceptions under a common application-specific base class — for example, an abstract PaymentException that InsufficientFundsException and CardDeclinedException both extend — lets calling code catch broadly ('any payment problem') or narrowly ('specifically insufficient funds') as needed. When you catch an exception only to add context before re-raising it, pass the original as the previous argument (the third constructor argument on Exception) so getPrevious() preserves the full causal chain for debugging.

🏏

Cricket analogy: A cricket board might classify rain interruptions and bad-light stoppages both under a broader 'PlayStoppageException,' letting officials react broadly or specifically, and note the original weather report as the 'previous' cause when escalating to the match referee.

A bare catch (Exception $e) that just does nothing (an empty catch body) silently destroys evidence of a bug. At minimum, log the exception. Swallowing exceptions without a trace is one of the most common causes of 'it just doesn't work and nobody knows why' production incidents.

Custom error and exception handlers

Beyond try/catch, PHP lets you install global hooks: set_exception_handler() catches any Throwable that escapes every catch block in the program (your last line of defense, typically used to log the error and show a generic message to users), and set_error_handler() intercepts traditional PHP errors and warnings (like accessing an undefined array index) so they can be converted into ErrorException objects and handled uniformly alongside real exceptions. Combining both means your application has a single, consistent path for reporting every kind of failure instead of two parallel systems.

🏏

Cricket analogy: A stadium's final safety officer is the last line of defense who intervenes if every other steward misses a crowd issue, while a separate protocol converts even minor incidents, like a spilled drink alert, into the same formal incident-report format used for serious ones.

  • All exceptions and internal engine errors implement Throwable; Exception and Error are its two main branches.
  • try/catch/finally separates normal logic from failure handling; finally always runs, even during an uncaught exception.
  • Catch specific exception types before their parent types — PHP matches the first compatible catch block in order.
  • Custom exception classes should extend RuntimeException or LogicException and carry structured data (typed properties), not just a string message.
  • Pass the original exception as the 'previous' constructor argument when rethrowing to preserve the full causal chain.
  • set_exception_handler() and set_error_handler() give you a global safety net for anything that escapes local try/catch blocks.

Practice what you learned

Was this page helpful?

Topics covered

#PHP#PHPProgrammingStudyNotes#Programming#ExceptionsAndErrorHandling#Exceptions#Error#Handling#Throwable#ErrorHandling#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse