PROGRAMMING-CONCEPTS

Exception / Error Handling: Definition, Purpose, and Examples

Exception handling is the way a program detects, reports, and responds to unexpected situations. An exception represents an event that disrupts the normal flow of a program — anything from invalid input to a missing file or a failed API request. Error handling ensures the program reacts predictably instead of crashing.

Every modern programming language includes tools for raising, catching, and managing errors. These tools help developers write safer code, protect user experience, and recover from problems gracefully.


Why Exceptions Exist

Programs live in an unpredictable environment. APIs might go offline. Users might type something unexpected. Files might not exist. Network connections fail. Even perfectly written code can run into cases it cannot control.

Without error handling, a single unexpected value might crash an entire application. Exceptions let developers:

  • Detect problems early
  • Isolate faulty code
  • Provide meaningful messages
  • Recover or retry operations
  • Avoid exposing internal program details to users

A well-written program expects things to go wrong and responds intelligently.


How Exceptions Work

While the syntax varies between languages, exceptions typically follow this process:

  1. Something goes wrong (invalid data, network failure, division by zero).
  2. The language throws an exception — signaling the error.
  3. If the code surrounding that operation includes a try/catch (or equivalent), the error is caught.
  4. The program runs the catch block and decides how to handle the issue.
  5. If no handler exists, the exception becomes fatal and stops execution.

This model ensures that errors are not silently ignored and that developers can control the recovery path.


Exception Handling Across Languages

Python

Python uses try, except, and optional finally blocks.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
finally:
    print("Cleanup complete.")

Python offers many built-in exception types (e.g., ValueError, TypeError, FileNotFoundError), making it easy to pinpoint problems.


JavaScript / TypeScript

JavaScript and TypeScript both use try, catch, and finally.

try {
  const data = JSON.parse("{ bad json }");
} catch (error) {
  console.log("Invalid JSON:", error.message);
} finally {
  console.log("Done.");
}

Developers often rely on error handling when working with asynchronous code, especially when using async/await.

async function loadUser() {
  try {
    const response = await fetch("/user");
    return await response.json();
  } catch (err) {
    console.error("Failed to load user");
  }
}

Swift

Swift uses do, try, and catch with typed errors.

enum FileError: Error {
    case missing
}

func loadFile() throws {
    throw FileError.missing
}

do {
    try loadFile()
} catch {
    print("File not found.")
}

Swift’s strict error typing improves reliability.


SQL

SQL doesn’t have traditional exception blocks, but many database systems (e.g., PostgreSQL, SQL Server) support error handling in stored procedures.

Example (SQL Server):

BEGIN TRY
    SELECT 1 / 0;
END TRY
BEGIN CATCH
    SELECT 'Error occurred';
END CATCH;

This helps preserve database integrity when running multi-step operations.


React

React doesn’t use try/catch for UI failures. Instead, it relies on Error Boundaries to catch errors in components.

class ErrorBoundary extends React.Component {
  componentDidCatch(error, info) {
    console.error("Component failed:", error);
  }

  render() {
    return this.props.children;
  }
}

This prevents the entire UI from breaking.


Common Types of Errors

1. Syntax Errors

Happen when code breaks language rules. These appear before the program runs.

Python example:

print("Hello"  # missing parenthesis

2. Runtime Errors

Appear while the program is executing.

const user = null;
console.log(user.name); // Cannot read properties of null

3. Logical Errors

The program runs successfully but produces incorrect results.

# Intended to sum numbers, but multiplies instead
total = a * b

Error handling can’t fix logic errors, but debugging tools help detect them.


Real-World Example: File Loading

A typical scenario where errors occur is reading user-provided files.

Python

def load_settings():
    try:
        with open("settings.json") as file:
            return file.read()
    except FileNotFoundError:
        return "{}"  # default settings

The program recovers by providing a fallback.


Real-World Example: API Requests

Network operations are fragile and must use error handling.

JavaScript

async function getWeather(city) {
  try {
    const res = await fetch(`/weather?city=${city}`);
    if (!res.ok) {
      throw new Error("API error");
    }
    return await res.json();
  } catch (e) {
    return { error: "Weather service unavailable" };
  }
}

This prevents broken APIs from breaking UI components.


Raising and Throwing Errors

Sometimes you must create your own exceptions to signal invalid conditions.

Python

def withdraw(balance, amount):
    if amount > balance:
        raise ValueError("Insufficient funds")
    return balance - amount

JavaScript

function validate(age) {
  if (age < 0) {
    throw new Error("Age cannot be negative");
  }
}

Custom errors help document assumptions and stop invalid data early.


Best Practices for Exception Handling

Good error handling aims for clarity, safety, and predictable behavior. These principles apply across languages:

Don’t swallow errors

Avoid empty catch blocks.

catch (e) {}  // Bad

This hides problems, making debugging harder.

Provide meaningful fallback behavior

If a file is missing, load defaults.

If an API fails, show a friendly message.

If input is invalid, prompt the user again.

Catch specific exceptions

Specific errors help pinpoint the cause.

Python:

except ValueError:
    ...

Instead of:

except Exception:
    ...

Don’t use exceptions for normal control flow

Exceptions should be rare events, not part of everyday logic.

Log errors for debugging

Errors that the user doesn’t see should still be recorded for developers.


Summary

Exception handling provides a structured way to detect, manage, and recover from errors. While the syntax differs across languages, the purpose stays consistent: keep programs stable, safe, and predictable. By anticipating failures and handling them gracefully, developers build applications that behave reliably — even when the unexpected happens.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster