Convert text to Integer, safely
Apex basics · Beginner · 12 min · Runs in your Salesforce Developer org · Free
Write `safeInt(String text, Integer fallback)` that returns the number inside `text`, or the fallback when the text is `null`, empty or not a number. Use `Integer.valueOf` to parse, and wrap the call in a `try/catch` so bad input returns the fallback instead of throwing.
Lesson
Why this matters
Salesforce code is often fed text from integrations, URL params or custom settings and has to turn it into a number. If the text is bad, the whole transaction should not blow up: the code should fall back to a sensible default and keep going.
The smallest working example
try {
return Integer.valueOf(text);
} catch (Exception error) {
return fallback;
}
For text = '42', this returns 42. For text = 'abc', the catch block runs and returns the fallback.
Name the parts
- **
Integer.valueOf(text)** parses the text and returns anInteger. On bad input it throws. - **
try { ... } catch (Exception error) { ... }** is Apex's way of saying "try this; if it throws, run the catch instead". - **The exception
error** can be any kind of Exception. Catching the baseExceptionis fine here because every parse failure is a kind of Exception.
A common wrong version
if (text == null || text == '') {
return fallback;
}
return Integer.valueOf(text);
This handles null and empty text, but Integer.valueOf('abc') still throws. The learner's method must catch that case too.
The fix
One try/catch covers all three bad cases: null, '', and non-numeric text. Integer.valueOf throws for every one of them.
Now you try
Finish safeInt with the try/catch above. Return Integer.valueOf(text) in the try block and fallback in the catch.
Learn more
The challenge
Write safeInt(String text, Integer fallback) that parses text with Integer.valueOf and returns the fallback on bad input.
Examples:
safeInt('42', -1)→42safeInt('abc', -1)→-1safeInt(null, 0)→0
Requirements:
safeInt('42', -1)should be42.safeInt('abc', -1)should be-1.safeInt(null, 0)should be0.safeInt('', -1)should be-1.safeInt('-7', 0)should be-7.safeInt('9', 0)should be9.safeInt('xx', 99)should be99.
Starter code
Integer safeInt(String text, Integer fallback) {
return fallback;
}
Related drills
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.