Java ProgramsExceptionsException Handling in Methods

Exception Handling in Methods in Java

intermediate·  Exceptions  ·  Error Handling

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.

Input
parseOrDefault("42"), parseOrDefault("abc")
Output
Parsed: 42 Parsed: -1

Java Program

Java
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

Parsed: 42 Parsed: -1

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.

How It Works
  1. 1parseOrDefault("42") parses successfully, so Integer.parseInt simply returns 42.
  2. 2parseOrDefault("abc") fails to parse, throwing a NumberFormatException inside the try block.
  3. 3The method's own catch (NumberFormatException e) handles that failure completely, returning -1 instead of letting the exception escape.
  4. 4Callers just get back an int either way — there's no throws clause, and no try-catch required at the call site.
Calling with "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.

Key Concepts

local exception handlingsentinel valuemethod design

Related Programs