Exception Handling in Methods in Java
Problem
A method can choose to absorb its own risky operation's failure entirely — catching it internally and returning a sentinel value — rather than letting the exception propagate out for a caller to deal with.
Write a method that safely converts text to a number, returning a default value instead of throwing when the text isn't a valid number.
Java Program
public class ExceptionHandlingInMethodsExample {
static int parseOrDefault(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return -1; // absorbs the failure here instead of letting it propagate
}
}
public static void main(String[] args) {
System.out.println("Parsed: " + parseOrDefault("42"));
System.out.println("Parsed: " + parseOrDefault("abc"));
}
}Output
Core Logic
Wrapping the risky parse in a try-catch inside the method itself, and returning a fixed fallback value from the catch block, means the caller never has to know a failure was even possible.
- 1
parseOrDefault("42")parses successfully, soInteger.parseIntsimply returns42. - 2
parseOrDefault("abc")fails to parse, throwing aNumberFormatExceptioninside the try block. - 3The method's own
catch (NumberFormatException e)handles that failure completely, returning-1instead of letting the exception escape. - 4Callers just get back an
inteither way — there's nothrowsclause, and no try-catch required at the call site.
"42" returns 42; calling with "abc" returns -1 instead of throwing, and both calls print normally with no exception ever visible to main().Key Point: This is the opposite design choice from letting an exception propagate up a call chain — here the method takes full responsibility for its own failure and hands back a plain value, at the cost of the caller being unable to tell a genuine failure apart from a real -1 result without extra context.