Beginner 25 min read

Handle Invalid Input

By the end of this lesson, you'll be able to:

  • Check for division by zero before it happens
  • Provide a fallback for an unrecognized operator
  • Explain why "fail loudly and clearly" beats a silent wrong answer

Prerequisites: "Build the Operations"

The problem: division by zero

Decimal result = 10 / 0;
// throws: System.MathException: Divide by 0
  1. Decimal result = 10 / 0; — dividing by zero.
  2. // throws: System.MathException: Divide by 0 — a comment documenting what actually happens.

Warning: Apex throws a runtime exception the instant line 1 executes, which crashes the whole transaction if nothing catches it. A calculator needs to check for this before dividing, not discover it via a crash.

Guarding division before it happens

when '/' {
    if (b == 0) {
        System.debug('Cannot divide by zero.');
        result = null;
    } else {
        result = a / b;
    }
}
  1. when '/' { — the division branch of the switch.
  2. if (b == 0) { — checks the risky condition first — this is the same if pattern from Module 6.
  3. System.debug('Cannot divide by zero.'); — runs only if b is genuinely 0.
  4. result = null; — no valid answer exists, so result stays empty rather than crashing.
  5. } else { — the safe path.
  6. result = a / b; — only performs the division once line 2 confirms it's actually safe.
  7. } — closes the if/else.
  8. } — closes the when '/' branch.

Handling an unrecognized operator

switch on operator {
    when '+' {
        result = a + b;
    }
    when '-' {
        result = a - b;
    }
    when '*' {
        result = a * b;
    }
    when '/' {
        result = (b == 0) ? null : a / b;
    }
    when else {
        System.debug('Unrecognized operator: ' + operator);
        result = null;
    }
}
  1. switch on operator { — checks the operator once. 2-4. when '+' { result = a + b; } — the addition branch. 5-7. when '-' { result = a - b; } — the subtraction branch. 8-10. when '*' { result = a * b; } — the multiplication branch. 11-13. when '/' { result = (b == 0) ? null : a / b; } — division, now guarded with the ternary operator (Module 6) instead of a separate if. 14-17. when else { ... } — when else (Module 6) catches anything that isn't one of the four known operators — a typo like 'x' for multiply now gets a clear debug message instead of silently doing nothing.
  2. } — closes the switch.

A real-world analogy: a smoke alarm, not a silent failure

A smoke alarm that stays silent during a fire is worse than useless — it gives false confidence. Code that returns a wrong or empty answer without saying why has the same problem: the caller has no idea something went wrong. Debugging a clear message (or, in later modules, throwing an exception) is the equivalent of the alarm actually sounding.

Exercise

Given Decimal a = 8, Decimal b = 0, String operator = '/', write the guarded division logic: debug "Cannot divide by zero." and set result to null if b is 0, otherwise perform the division.

Show hint

if (b == 0) { ... } else { result = a / b; }

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Handle Invalid Input Quiz

1. What happens if you divide by zero in Apex without a guard?

2. when else in a switch statement is the equivalent of a trailing else in an if/else if chain.

Log in to submit the quiz and save your score.

Leaderboard

  • 1. Monde Masiza 2/2

My Notes

Log in to keep private notes on this lesson.

Questions about this lesson

No questions yet — be the first to ask.

Log in to ask a question about this lesson.

Summary

A calculator that crashes or silently returns nonsense on bad input isn't trustworthy — this lesson adds the checks planned in Lesson 1: division by zero and unrecognized operators.