Messages for users versus developers
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Every error has two audiences. The user needs one calm sentence that says what went wrong and what to do; the developer needs every technical detail. Mixing them up gives users stack traces and gives developers nothing to debug with.
What a good message says: what, which value, what to do
A user message is the text a person sees when something goes wrong. A good one answers three questions in plain words: what went wrong, which value caused it, and what the user can do now.
Example 1 · A bad message and a good message for the same problem
public class GoodMessageDemo { static String badMessage(String upiId, int amount) { if (!upiId.contains("@")) return "Error: invalid input"; if (amount > 100000) return "Error code 4"; return "OK"; }
static String goodMessage(String upiId, int amount) { if (!upiId.contains("@")) { return "The UPI ID '" + upiId + "' is missing the @ part. " + "Use the form name@bank, for example riya@okaxis."; } if (amount > 100000) { return "Rs " + amount + " is above this app's limit of Rs 100000 per payment. " + "Split it into smaller payments."; } return "OK"; }
public static void main(String[] args) { String[] ids = {"riya.okaxis", "riya@okaxis", "riya@okaxis"}; int[] amounts = {500, 250000, 500}; for (int i = 0; i < ids.length; i++) { System.out.println("Bad: " + badMessage(ids[i], amounts[i])); System.out.println("Good: " + goodMessage(ids[i], amounts[i])); } }}Bad: Error: invalid input Good: The UPI ID 'riya.okaxis' is missing the @ part. Use the form name@bank, for example riya@okaxis. Bad: Error code 4 Good: Rs 250000 is above this app's limit of Rs 100000 per payment. Split it into smaller payments. Bad: OK Good: OK
What this code does
- Both methods find the same two problems. The bad messages hide what happened;
Error code 4means something only to whoever wrote the code. - Each good message names the problem, shows the value the user typed, and says exactly what to do next.
Error: invalid input answers none of them. The UPI ID 'riya.okaxis' is missing the @ part. Use the form name@bank, for example riya@okaxis. answers all three, so the user can fix it in seconds without calling anyone. Keep it short, polite and free of blame. Do not show exception class names, error numbers without meaning, or words like "null" and "exception".
No stack traces on the user's screen
A developer message is for the people who fix the program: the exception class, its message, the cause and the stack trace. It belongs in the log, never on the user's screen.
Example 2 · Friendly message for the user, details for the developer
import java.util.ArrayList;import java.util.List;
public class FriendlyErrorDemo { static List<String> developerLog = new ArrayList<>(); static int nextRef = 1001;
static String receipt(String roll, Integer amount) { return "Receipt for " + roll + ": Rs " + amount.intValue(); // bug: amount can be null }
static void handle(String roll, Integer amount) { try { System.out.println(receipt(roll, amount)); } catch (RuntimeException e) { String ref = "ERR-" + nextRef++; System.out.println("Sorry, we could not create your receipt. Please try again later. Reference: " + ref); String where = e.getStackTrace()[0].getMethodName(); developerLog.add(ref + " " + e.getClass().getName() + " in " + where + " for roll " + roll); } }
public static void main(String[] args) { handle("101", 45000); handle("102", null); System.out.println("--- developer log (never shown to users) ---"); developerLog.forEach(System.out::println); }}Receipt for 101: Rs 45000 Sorry, we could not create your receipt. Please try again later. Reference: ERR-1001 --- developer log (never shown to users) --- ERR-1001 java.lang.NullPointerException in receipt for roll 102
What this code does
- The user sees one calm sentence and a reference id, with no class names, no
nulland no stack trace. - The developer entry has the same id, the exception class and the method where it was thrown. A real program sends this, with the full stack trace, to a log file, as the next lesson shows.
A stack trace scares users, tells them nothing they can act on, and can reveal class names, file paths and library versions to anyone curious. The top of the program should catch what is left, show a calm sentence, and hand the full details to the log. A common trick links the two: show a short reference id such as ERR-1001 to the user and write the same id in the log. When the user reports it, support finds the exact log entry.
No passwords or personal data in messages
Messages and logs are read by many people and kept for a long time, so they must never contain passwords, OTPs, card numbers, Aadhaar numbers or similar secrets. If a value must appear, mask it: show only a small part, as in 98******10.
Example 3 · Masking personal data and a safe login error
import java.util.Map;
class LoginFailedException extends RuntimeException { LoginFailedException(String userId) { super("Login failed for user " + userId); // never include the password }}
public class PrivacyDemo { static Map<String, String> passwords = Map.of("riya@college.edu", "Mango#2024");
static String maskPhone(String phone) { return phone.substring(0, 2) + "******" + phone.substring(8); }
static String maskCard(String card) { return "**** **** **** " + card.substring(card.length() - 4); }
static void login(String user, String password) { String saved = passwords.get(user); if (saved == null || !saved.equals(password)) { throw new LoginFailedException(user); // same exception for both cases } System.out.println("Welcome " + user); }
public static void main(String[] args) { String[][] attempts = {{"riya@college.edu", "mango2024"}, {"nobody@college.edu", "x"}}; for (String[] a : attempts) { try { login(a[0], a[1]); } catch (LoginFailedException e) { System.out.println("User sees: Invalid email or password."); System.out.println("Log: " + e.getMessage()); } } System.out.println("OTP sent to " + maskPhone("9876543210")); System.out.println("Paid with card " + maskCard("4111111111111111")); }}User sees: Invalid email or password. Log: Login failed for user riya@college.edu User sees: Invalid email or password. Log: Login failed for user nobody@college.edu OTP sent to 98******10 Paid with card **** **** **** 1111
What this code does
- A wrong password and an unknown email produce the same user message, so nobody can use the login page to test which emails are registered. The typed password never reaches the exception or the log.
maskPhonekeeps the first 2 and last 2 digits, andmaskCardkeeps the last 4: enough for the user to recognise their number, useless to anyone else.
A masked card looks like **** **** **** 1111.
Login errors need extra care. Say Invalid email or password, not Wrong password for riya@college.edu, so an attacker cannot learn which emails have accounts. Privacy laws, such as India's Digital Personal Data Protection Act, 2023, also expect apps to protect personal data like this.
Exit codes for command-line programs
An exit code is the number a program hands back to the operating system when it ends. 0 means success; any other number means failure. The commands below show how to read it.
java MarksAverage 78,9l,66echo $? # macOS / Linux: prints the exit code, here 3echo %ERRORLEVEL% # Windows Command Promptecho $LASTEXITCODE # Windows PowerShellExample 4 · Exit codes from a small command-line tool
import java.io.PrintStream;
public class ExitCodeDemo { static final int OK = 0; static final int USAGE = 2; static final int DATA_ERROR = 3;
// The real program's main would be: // System.exit(run(args, System.out, System.err)); static int run(String[] args, PrintStream out, PrintStream err) { if (args.length != 1) { err.println("Usage: java MarksAverage <marks separated by commas>"); return USAGE; } String[] parts = args[0].split(","); int total = 0; for (String p : parts) { try { total += Integer.parseInt(p.trim()); } catch (NumberFormatException e) { err.println("Error: '" + p + "' is not a whole number. Fix the marks list and run again."); return DATA_ERROR; } } out.println("Average: " + total / parts.length); return OK; }
public static void main(String[] args) { // Three sample runs. Errors go to System.out here so they show on this page. String[][] runs = {{"78,91,66"}, {}, {"78,9l,66"}}; for (String[] r : runs) { System.out.println("> java MarksAverage " + String.join(" ", r)); int code = run(r, System.out, System.out); System.out.println("exit code " + code); } }}> java MarksAverage 78,91,66 Average: 78 exit code 0 > java MarksAverage Usage: java MarksAverage <marks separated by commas> exit code 2 > java MarksAverage 78,9l,66 Error: '9l' is not a whole number. Fix the marks list and run again. exit code 3
What this code does
runreturns a code instead of callingSystem.exititself, so it is easy to test: the demo calls it three times in one program.- In the real tool,
mainpassesSystem.errfor errors and callsSystem.exit(run(...)), so a script sees0,2or3and knows exactly what happened. The typo9l(letter l) gets a message that names the value.
System.exit(code) sets the exit code, and a main that ends with an uncaught exception exits with 1 after printing a stack trace.
Scripts and build tools check the exit code to decide whether to continue, so a command-line tool should return a clear code for each kind of failure. A common habit is 2 for wrong usage (missing or extra arguments). Error text goes to System.err, so normal output on System.out stays clean.
Next step
Check your understanding
12 quick questions