100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
HomeBlogPython Error Handling: try, except, finally Explained
Programming

Python Error Handling: try, except, finally Explained

SV

SkillVeris Team

Engineering Team

May 25, 2026 9 min read
Share:
Python Error Handling: try, except, finally Explained
Key Takeaway

Catch specific exceptions, not a bare except, so real bugs surface instead of being silenced.

In this guide, you'll learn:

  • Use finally for cleanup that must always run, like closing files and releasing connections.
  • Raise custom exceptions for domain errors so callers can catch exactly what they expect.
  • Chain exceptions with 'raise NewError(...) from e' to preserve the full debugging context.
  • Log exceptions with exc_info=True before re-raising to capture the full traceback in production.

1Why Error Handling Matters

Every program encounters unexpected situations: files that don't exist, network requests that time out, user input that isn't a valid number, database connections that drop. Without error handling, these situations crash the program with a traceback that the user sees.

With good error handling, the program responds gracefully — logging the error, showing a helpful message, retrying if appropriate, or failing with clear diagnostic information for the developer.

Good error handling is the difference between a production-ready application and a fragile script.

2Python's Exception Hierarchy

Python exceptions form a class hierarchy — catching a parent catches all its children. Understanding this structure tells you which exceptions are related and how broadly an except clause will reach.

Catching a parent class catches all its subclasses: except Exception catches everything except SystemExit and KeyboardInterrupt. Always catch the most specific exception you can name.

The Core Hierarchy

The most important structure to keep in mind:

code
BaseException
  SystemExit          # raised by sys.exit()
  KeyboardInterrupt   # Ctrl+C
  Exception           # base of most user-facing exceptions
    ValueError        # wrong value: int("hello")
    TypeError         # wrong type: "a" + 1
    KeyError          # missing dict key: d["missing"]
    IndexError        # index out of range: lst[999]
    FileNotFoundError # file does not exist
    ConnectionError   # network failure
    PermissionError   # access denied
    ZeroDivisionError # x / 0

3try and except

Python executes the try block until an exception occurs. If an exception matches the except clause, that block runs and execution continues after the try/except.

If no exception occurs, the except block is skipped entirely.

Basic Structure

A minimal try/except that falls back to a default value:

code
# Basic structure
try:
    result = int("not a number")  # raises ValueError
except ValueError:
    result = 0
    print("Could not convert to int, using default 0")
print(result)  # 0

4Catching Specific Exceptions

Catch multiple exception types either in separate except clauses or as a tuple: except (FileNotFoundError, PermissionError). The as e syntax binds the exception object to a variable, giving you access to its message and attributes.

⚠️Watch Out

Never use a bare except: without specifying the exception type. It catches everything, including SystemExit, KeyboardInterrupt, and programming mistakes like NameError. You hide real bugs and make programs impossible to interrupt. Always name the exception you expect.

Handling Each Failure Distinctly

Each except clause can respond to its specific failure mode:

code
def load_config(path: str) -> dict:
    try:
        with open(path) as f:
            import json
            return json.load(f)
    except FileNotFoundError:
        print(f"Config file {path!r} not found, using defaults")
        return {}
    except json.JSONDecodeError as e:
        print(f"Config file has invalid JSON: {e}")
        return {}
    except PermissionError:
        raise  # re-raise: this is a serious problem we can't handle

5The else Clause

The else block runs only if the try block succeeded without raising an exception. It's the correct place for code that should only run when no error occurred — cleaner than putting it at the end of the try block.

The distinction: code in try is protected; code in else is not. If the else code raises an exception, the except clause doesn't catch it (by design: it would catch errors we didn't intend).

Python exceptions form a class hierarchy — catching a parent catches all its children.
Python exceptions form a class hierarchy — catching a parent catches all its children.

Using else for the Success Path

Code that depends on a successful try belongs in else:

code
try:
    value = int(user_input)
except ValueError:
    print("Please enter a valid integer")
else:
    # Only runs if int() succeeded
    result = value * 2
    print(f"Double your number: {result}")

6finally: Always Runs

finally runs whether or not an exception occurred — perfect for cleanup that must always happen, such as closing files, releasing database connections, or releasing locks.

In modern Python, the with statement handles most resource cleanup automatically (it calls __exit__ even on exception), making explicit finally less necessary for file handling. Use with for files and connections; use finally when you need custom cleanup that context managers don't handle.

Guaranteed Cleanup

The finally clause closes the file even when the body raises:

code
def process_file(path: str) -> str:
    f = open(path)
    try:
        data = f.read()
        result = data.upper()  # might fail on binary files
        return result
    except UnicodeDecodeError as e:
        raise ValueError(f"File {path} is not text: {e}") from e
    finally:
        f.close()  # always closes, even if exception occurred

7Raising Exceptions

Raise exceptions to signal that something is wrong that the caller should handle. Write clear, specific messages that include the problematic value: "age must be between 0 and 150, got -5" is far more useful in a log than "invalid age".

Raising and Re-raising

Validate inputs by raising, and re-raise after logging when you can't recover:

code
def set_age(age: int) -> None:
    if not isinstance(age, int):
        raise TypeError(f"age must be an int, got {type(age).__name__}")
    if age < 0 or age > 150:
        raise ValueError(f"age must be between 0 and 150, got {age}")
    # proceed with valid age

# Re-raising
try:
    risky_operation()
except ConnectionError as e:
    log.error(f"Connection failed: {e}")
    raise  # re-raise the same exception with its traceback

8Exception Chaining

Use raise NewException(...) from original_exception to preserve the original error context when converting exception types.

The from e syntax sets the __cause__ attribute, showing the full chain of exceptions in the traceback. This makes debugging dramatically easier: you see both what went wrong at the domain level and what went wrong at the implementation level.

Converting Low-Level Errors

Chaining keeps the original cause visible while presenting a domain-level error:

code
def load_user(user_id: int) -> dict:
    try:
        return db.query(f"SELECT * FROM users WHERE id = {user_id}")
    except DatabaseError as e:
        # Convert low-level DB error to domain-level error
        raise UserNotFoundError(
            f"Could not load user {user_id}"
        ) from e  # chains: both tracebacks appear in output

9Custom Exception Classes

Define custom exceptions for domain-specific error conditions. This lets callers catch your specific errors without catching unrelated ones.

Defining and Using a Hierarchy

A shared base class plus specific subclasses gives callers fine-grained control:

code
# Define your exception hierarchy
class AppError(Exception):
    # Base class for all application errors
    pass

class ValidationError(AppError):
    def __init__(self, field: str, message: str):
        self.field = field
        self.message = message
        super().__init__(f"Validation error on '{field}': {message}")

class NotFoundError(AppError):
    def __init__(self, resource: str, identifier):
        super().__init__(f"{resource} with id '{identifier}' not found")

# Usage
def validate_email(email: str) -> None:
    if "@" not in email:
        raise ValidationError("email", "must contain @")

try:
    validate_email("notanemail")
except ValidationError as e:
    print(f"Field: {e.field}, Error: {e.message}")

10Logging Exceptions

exc_info=True includes the full traceback in the log output — essential for debugging production issues. Use log.warning for expected failure conditions (a declined card) and log.error for unexpected failures that need investigation.

The four correct patterns: catch specific, log and re-raise, return a default, raise a custom exception.
The four correct patterns: catch specific, log and re-raise, return a default, raise a custom exception.

Logging in Production Code

Match the log level to the severity, and re-raise when a human needs to act:

code
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

def process_payment(amount: float, card_token: str) -> bool:
    try:
        result = payment_gateway.charge(amount, card_token)
        log.info(f"Payment of {amount} processed successfully")
        return True
    except CardDeclinedError as e:
        log.warning(f"Card declined for amount {amount}: {e}")
        return False
    except PaymentGatewayError as e:
        log.error(f"Gateway error for amount {amount}", exc_info=True)
        raise  # re-raise: this needs human attention

11Common Anti-Patterns

Most error-handling mistakes share a root cause: catching too broadly or swallowing failures silently. The table below pairs each anti-pattern with the problem it causes and the fix to apply.

  • bare except: — Catches everything including bugs · Fix: except SpecificError:
  • Silent swallowing (except Exception: pass) — Hides failures · Fix: log it, at minimum
  • Catching and ignoring — Hides bugs that should be fixed · Fix: let it propagate
  • String-based errors (return "Error: file not found") — Not a real exception · Fix: raise FileNotFoundError
  • try wrapping everything (try: entire 100-line function) — Obscures the failing line · Fix: wrap only the failing line

12Key Takeaways

The core practices for robust Python error handling come down to specificity, guaranteed cleanup, and informative logging.

  • Always catch specific exceptions — never a bare except:.
  • finally runs regardless of exception status; use it for cleanup.
  • raise NewError(...) from original chains exceptions, preserving the full debugging context.
  • Define custom exception classes for domain-specific errors; callers can catch exactly what they expect.
  • Log with exc_info=True before re-raising to capture the full traceback in production logs.

13What to Learn Next

Go deeper in Python best practices with these related topics:

  • Python OOP — custom exceptions are a natural extension of class design.
  • Async Python — exception handling in async contexts follows the same patterns.
  • Build a REST API with FastAPI — exception handlers in FastAPI return HTTP error responses.

14Frequently Asked Questions

Q: Should I always use try/except for things that might fail?

A: Python style favours EAFP (Easier to Ask Forgiveness than Permission): try the operation and handle the exception, rather than checking conditions before every operation. For example, try: value = d[key] except KeyError: ... is more Pythonic than if key in d: value = d[key] else: ... . But don't overdo it — wrap only the specific lines that might raise, not entire functions.

Q: What is the difference between raise and raise e?

A: Bare raise re-raises the current exception with its original traceback intact. raise e raises the exception as if it originated at that line, losing the original traceback location. Always use bare raise when re-raising; use raise NewException(...) from e when wrapping.

Q: When should I define a custom exception vs use a built-in?

A: Use built-in exceptions when they accurately describe the error (ValueError for wrong values, TypeError for wrong types, FileNotFoundError for missing files). Create custom exceptions when the error is domain-specific and callers need to catch it separately from unrelated errors.

Q: What does exc_info=True do in logging?

A: It appends the current exception's traceback to the log record. Without it, you only log the message. With it, you log the full exception class, message, and traceback — which is what you need to diagnose a production error from a log file.

📄

Get The Print Version

Download a PDF of this article for offline reading.

About the Publisher

SV

SkillVeris Team

Engineering Team

Our engineering writers turn abstract code concepts into hands-on, project-driven learning experiences.

View all posts

Never miss an update

Get the latest tutorials and guides delivered to your inbox.

No spam. Unsubscribe anytime.

Frequently Asked Questions

21 categories · pick one to explore

Does SkillVeris have a tech blog, and what does it cover?
Yes, the SkillVeris blog has over 500 articles covering AI and machine learning, programming, web development, DevOps, cloud, security, databases and career guidance. Articles are practical and answer-first, and many use the Learn Through Hobbies approach, teaching technical concepts through cricket, music, gaming or cooking analogies. Everything is free to read.
What is the SkillVeris tech glossary and how big is it?
The SkillVeris glossary is a free reference of roughly 2,000-plus technology terms, each with a clear plain-language definition. It spans AI, programming, web, DevOps, cloud, security and database vocabulary, so whenever a lesson, article or job description uses jargon you do not recognise, the glossary gives you a fast, reliable answer.
Are the developer cheat sheets on SkillVeris free to download?
The cheat sheets are completely free to use, like everything else on SkillVeris. Each sheet condenses a language or tool into its essential syntax, commands and patterns for quick reference while coding. They are designed for rapid lookup during real work, complementing the deeper explanations found in study notes and courses.
Which programming references and cheat sheets are available?
Cheat sheets cover the platform's main domains, including programming languages, AI and ML tooling, web development, DevOps, cloud, security and databases, matching the topics of the 37 live courses. Each sheet lists related reading links and hashtags, so you can jump from a quick reference into fuller study notes or blog articles.
How do I find the meaning of a technical term quickly?
Search the SkillVeris glossary, which holds around 2,000-plus terms with concise, plain-language definitions. Each entry gets to the point in its first sentence, then links to related reading like blog posts or study notes for deeper context. It is faster and more consistent than sifting through scattered search results.
Is the SkillVeris blog good for beginners learning to code?
Yes, many blog articles are written specifically for beginners, and the Learn Through Hobbies style makes them unusually approachable: you might learn Python concepts through cricket or understand APIs through cooking. With 500-plus articles across skill levels, beginners can start with fundamentals and keep reading as they advance, entirely free.
Can cheat sheets replace full courses for learning a language?
No, cheat sheets are references, not teaching tools; they assume you already understand the concepts and just need syntax or commands fast. To actually learn a language, take a structured SkillVeris course with its 24–40 lessons and assessments, then keep the cheat sheet beside you while practising in Code Lab.
How often are new blog articles published on SkillVeris?
The blog grows regularly and already exceeds 500 articles, with new posts added as courses launch and technologies evolve. Topics track the platform's catalogue across AI, programming, web development, DevOps, cloud and security, so checking the Blog section periodically surfaces fresh tutorials, explainers and career-focused pieces, all free to read.
Does the glossary cover AI and machine learning terms?
Yes, AI and machine learning vocabulary is a major part of the roughly 2,000-plus term glossary, covering everything from foundational terms to modern concepts around LLMs, RAG and MLOps. Definitions are plain-language and answer-first, which helps when dense AI papers or course lessons throw unfamiliar jargon at you.
Are there cheat sheets for interview preparation?
Cheat sheets work well as interview-day refreshers because they compress syntax, commands and key concepts into scannable references. For dedicated preparation, combine them with the SkillVeris interview questions feature, which includes readiness scoring, plus study notes for depth. Reviewing a relevant cheat sheet just before an interview steadies recall under pressure.
Can I read the tech blog without signing up?
Yes, the blog is freely readable, and SkillVeris never charges for content. All 500-plus articles are open, covering tutorials, concept explainers and career advice. Creating a free account adds value elsewhere on the platform, like course progress tracking and certificates, but reading the blog requires no commitment at all.
How is the SkillVeris glossary different from Wikipedia?
The glossary is purpose-built for learners: definitions are short, plain-language and answer-first, sized for a quick lookup mid-lesson rather than a deep encyclopedic read. Entries also cross-link to related SkillVeris study notes, blog posts and courses, so a definition becomes a doorway into structured learning instead of a dead end.
Do blog articles use the Learn Through Hobbies method?
Many blog articles teach technical topics through hobby analogies, a hallmark of the SkillVeris blog, so you will find articles explaining programming through cricket, machine learning through music, or system design through cooking. The analogy is the teaching device; the article still delivers the real technical concept underneath.
Where can I find quick programming references while coding?
Open the SkillVeris cheat sheets, which are built exactly for that moment: compact, scannable references for syntax, commands and common patterns across languages and tools. Keep the relevant sheet in a browser tab while you work in Code Lab or your own editor, and dip into the glossary for terminology.
Is there a glossary entry for terms I meet in job descriptions?
Very likely yes, with roughly 2,000-plus terms across AI, programming, web, DevOps, cloud, security and databases, the glossary covers most jargon that appears in tech job descriptions. Decoding a listing this way helps you judge role fit honestly and prepares you to discuss those terms in interviews.
Are the blog articles written for the Indian tech audience?
The blog serves Indian learners plus a worldwide audience. Content stays globally relevant while acknowledging realities that matter in India, such as free access being essential for students and freshers, and career guidance that connects naturally to the SkillVeris jobs portal, which aggregates roles across India, UK, USA, Germany and Remote.
Can I suggest a topic for the blog or glossary?
SkillVeris content grows in response to what learners need, so feedback is welcome through the platform's support channels. If a term is missing from the glossary or a topic deserves an article, telling the team helps prioritise it. Meanwhile, the AI Mentor can answer the question immediately, 24/7, at any depth.
Do cheat sheets and glossary entries link to deeper learning?
Yes, every cheat sheet and glossary entry carries related reading links into study notes, blog articles and courses, plus concept hashtags for discovering similar content. This cross-linking means a thirty-second lookup can smoothly become a structured learning session whenever you decide you want more than a quick answer.
What makes SkillVeris programming references trustworthy?
The references are written to strict internal quality standards, kept consistent with the platform's 37 live courses, and never padded with invented statistics or hype. Definitions and cheat sheets are reviewed against the same content contracts that govern courses, and the answer-first style makes any inaccuracy easy to spot and correct.
How do the blog, glossary and cheat sheets fit into my learning routine?
Use them as satellites around your main course: read blog articles for context and motivation, hit the glossary the instant jargon appears, and keep cheat sheets open while coding. Together with study notes, Code Lab and the 24/7 AI Mentor, they turn passive reading into a complete, free learning system.

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