An exception type communicates a failure category. Some exceptions are checked: Java requires a method either to catch them or to declare them with throws. IllegalArgumentException is unchecked; IOException is checked. Choose error handling by who can recover, not by adding catch blocks until the compiler stops complaining.
Work through the example
throw creates a failure at a particular point. throws in a method signature advertises that callers must handle a checked failure. Our small InvalidLine extends Exception and carries a useful message through the parent constructor.
This custom type is a teaching example, not a requirement for every validation method. Use it when a distinct category helps callers recover differently. The catch handles only InvalidLine. Unexpected programming errors would still escape rather than being mistaken for a rejected user line.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
public class Main {
public static void main(String[] args) {
try {
System.out.println(requireTitle(" "));
} catch (InvalidLine error) {
System.out.println(error.getMessage());
}
System.out.println("Still running");
}
static String requireTitle(String text) throws InvalidLine {
if (text == null || text.trim().isEmpty()) {
throw new InvalidLine("title required");
}
return text.trim();
}
}
final class InvalidLine extends Exception {
InvalidLine(String message) {
super(message);
}
}Check your prediction
title required
Still runningCompare the behavior
Catching a failure should not fabricate success. This caller counts accepted input separately from rejected input. The method's result is used only after validation succeeds. A precise catch makes it clear which operation can reject the line.
public class Main {
public static void main(String[] args) {
int accepted = 0;
for (String text : new String[] {"Read", " "}) {
try {
String title = requireTitle(text);
System.out.println(title);
accepted++;
} catch (InvalidLine error) {
System.out.println("Rejected");
}
}
System.out.println(accepted);
}
static String requireTitle(String text) throws InvalidLine {
if (text == null || text.trim().isEmpty()) {
throw new InvalidLine("title required");
}
return text.trim();
}
}
final class InvalidLine extends Exception {
InvalidLine(String message) {
super(message);
}
}Check your prediction
Read
Rejected
1Separate the failure category from the recovery location
A checked exception declaration makes the possibility visible to callers. It does not choose a recovery policy for them. A lower-level parser can declare a distinct failure, while a loop at the input boundary catches it, records a message and decides whether to continue.
throw and throws occupy different places: throw executes a statement that transfers control; throws belongs to a method signature that declares a possible failure. Constructing an exception with new supplies its message, and super(message) passes that message to the parent exception implementation.
Test both successful and rejected calls. Then remove a catch temporarily and read the compile-time requirement. Restoring it with an empty catch would satisfy the compiler but could hide rejected work; a useful handler must still follow the application's contract. Avoid treating “no compiler complaint” as evidence that recovery is correct.
Practice independently
Checked Exceptions: practice
Create checked InvalidCode extends Exception. requireCode(String) accepts exactly two trimmed characters; otherwise throw InvalidCode with two characters required. Handle it in main. Print A1 for " A1 " and the rejection message for "ABC".
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
public class Main {
public static void main(String[] args) {
System.out.println("Declare and handle a checked failure");
}
}Hint 1: the idea
A checked exception is a class plus a declaration at the method boundary. The caller needs a policy.
Hint 2: a first step
Call super(message) in the exception constructor, and add throws InvalidCode to requireCode.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
public class Main {
public static void main(String[] args) {
for (String text : new String[] {" A1 ", "ABC"}) {
try {
System.out.println(requireCode(text));
} catch (InvalidCode error) {
System.out.println(error.getMessage());
}
}
}
static String requireCode(String text) throws InvalidCode {
if (text == null || text.trim().length() != 2) {
throw new InvalidCode("two characters required");
}
return text.trim();
}
}
final class InvalidCode extends Exception {
InvalidCode(String message) {
super(message);
}
}Expected output:
A1
two characters requiredChange it and test again
Remove the throws declaration temporarily and read the compiler error. Restore it, then remove the caller's catch and observe the next error. Finally compare this failure with the repository's normal missing lookup, represented by null. A routine absence and malformed input need different policies; no new result-wrapper type is required here.
Explain before moving on
Explain throw versus throws. Why is catching Throwable or Exception around a whole test likely to hide a defect?
Completion is saved in this browser only. It does not measure mastery.