Open-Source Java Programming • Foundational • Estimated study time: 45 minutes.
Monitoring applications need to distinguish a valid reading from a failed sensor, invalid text or inaccessible resource. Java exceptions make these abnormal outcomes explicit. This lesson follows Java generics and collections.
Learning objectives
Distinguish checked and unchecked exceptions; use throw, throws, try and catch; explain when finally executes; automatically close an AutoCloseable resource; preserve measurement integrity when input is invalid.
The exception contract
A checked exception, such as IOException, generally must be caught or declared in a method’s throws clause. RuntimeException and its subclasses are unchecked. Throwing transfers control to a matching handler, or propagates the exception to the caller. Catch specific subclasses before broader types. NumberFormatException extends IllegalArgumentException, so reversing those two catch clauses in the example would make the specific handler unreachable. See Dev.java’s exception handling guide.
Dev Portal: tutorial on try/catch and try-with-resources. Review the official Java documentation alongside the video.
Resource lifetime
The try-with-resources statement closes resources that implement AutoCloseable after the block completes, even when an exception occurs. Resources close in reverse initialization order. If work and closing both fail, the closing failure is normally attached as a suppressed exception. A finally clause is useful for other cleanup, but should not return a value or throw unnecessarily because this can obscure the original failure. Review Java I/O resource management.

Worked example: valid and invalid telemetry batches
A batch mean is T̄ = Σ Ti / n, where Ti is a valid reading in degrees Celsius and n is the number of readings. For 24 and 26 °C, T̄ = 25 °C. This deliberately strict batch parser rejects the entire batch when any reading is invalid. The program builds on Java methods, strings and interfaces. The in-memory reader avoids production dependencies.
import java.io.*;
import java.util.Locale;
public class Telemetry {
static double mean(String input) throws IOException {
double total = 0;
int count = 0;
try (BufferedReader r = new BufferedReader(new StringReader(input))) {
String line;
while ((line = r.readLine()) != null) {
double value = Double.parseDouble(line.strip());
if (!Double.isFinite(value)) throw new IllegalArgumentException("nonfinite reading");
total += value;
count++;
}
}
if (count == 0) throw new IllegalArgumentException("empty batch");
return total / count;
}
public static void main(String[] args) {
for (String batch : new String[]{"24\n26", "24\noffline", "", "NaN"}) {
try {
System.out.printf(Locale.ROOT, "mean=%.1f C%n", mean(batch));
} catch (NumberFormatException e) {
System.out.println("invalid numeric reading");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println("read failed");
}
}
}
}
Compile and execute: javac -Xlint:all -Werror Telemetry.java, then java Telemetry. OpenJDK 21.0.12.1 successfully compiled and ran the exact source. Actual output:
mean=25.0 C
invalid numeric reading
empty batch
nonfinite reading
Community discussion on resource management and checked exceptions; the Java language documentation governs behavior.
Operational safety and limitations
Never convert failed readings to zero without a documented reason. In a real system, store timestamps, validity and error context, set input and numeric limits, and distinguish transient communication errors from permanent configuration failures. A sum of individually finite values can still overflow, so production code should bound plausible readings or use a numerically robust aggregation method. Avoid running a demonstration as an actual equipment control loop.
Exercises and answer key
A. Is IOException checked? B. Why catch NumberFormatException first? C. What closes the reader? D. What does mean(“20\n22”) return? E. Why reject NaN? F. Why should an empty batch not produce zero?
Answers: A. Yes. B. It is a subclass of IllegalArgumentException. C. try-with-resources. D. 21.0. E. NaN would invalidate arithmetic. F. There is no valid denominator or observed temperature.
Featured cover: AI-generated oil-painting-style editorial illustration. The pictured code is conceptual; use the tested example in this lesson.
Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please scan the QR code below

For mobile scanning, open the article on another display and scan the QR code with a Bitcoin wallet. The voluntary donation amount is 5,000 sats. Verify the receiving address 3C9o19EH5HSiwEPyCTmEKzxhNCbo2X6TTb before sending.
BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

Leave a Reply