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

Apex throws a runtime exception the instant this line 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;
    }
}

This is the same if pattern from Module 6 — check the risky condition first, and only perform the division when it's actually safe.

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;
    }
}

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.

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; }

APEX

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.

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.