Loading
0x70Lesson 8 of 9

Handle exceptions and validate input

Use try/catch to keep programs reliable with imperfect input.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • Catch conversion errors and continue with safe behavior.

Java uses exceptions to represent runtime errors. try/catch lets you handle expected failures such as invalid number parsing. This is essential for robust command-line tools and backend input processing.

Main.java
1String[] tokens = {"10", "oops", "7"};
2int total = 0;
3for (String token : tokens) {
4    try {
5        total += Integer.parseInt(token);
6    } catch (NumberFormatException ignored) {
7    }
8}
9System.out.println(total);
Output
17

Catch specific exceptions when possible. NumberFormatException is thrown when text cannot be parsed as an integer. In larger apps, log invalid records instead of silently dropping them.

Key takeaways

  • Catch conversion errors and continue with safe behavior.

  • Java checks types as it compiles your source.

  • Use compiler messages as clues about what needs fixing.

Lesson quiz

4 questions · pass with 3 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Java

Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.

Exercise 1

Sum valid integers only

+25 XP

Read an integer n, then n tokens. Sum only tokens that parse as integers and print the total.

  • Mixed tokens
  • All invalid
Main.java
Loading editor…

Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…