You can catch an exception, and deal with it, instead of letting the program crash. Put the risky code in a try block, and the rescue code in a catch block.
Parse int throws a number format exception, when the text isn't a number. We put it inside try. If it throws, Java jumps straight to the catch block. Get message describes the problem. Then the loop carries on, as normal. Run it. Forty two and eight are added. Seven, written as a word, is skipped. And the total is fifty.
Main.javajava
public class Main { public static void main(String[] args) { String[] inputs = {"42", "seven", "8"}; int total = 0; for (String s : inputs) { try { int n = Integer.parseInt(s); total += n; System.out.println("Added " + n); } catch (NumberFormatException e) { System.out.println("Skipped '" + s + "': " + e.getMessage()); } } System.out.println("Total: " + total); }}
One try can have several catch blocks, for different exceptions. Java uses the first one that matches. A vertical bar catches two types in one block. Run it. Four. Not a number. Arithmetic exception, from dividing by zero. And an index out of bounds.
Main.javajava
public class Main { static void test(String text, int index) { try { int n = Integer.parseInt(text); int[] data = {10, 20, 30}; System.out.println(data[index] / n); } catch (NumberFormatException e) { System.out.println("Not a number: " + text); } catch (ArithmeticException | ArrayIndexOutOfBoundsException e) { System.out.println("Problem: " + e.getClass().getSimpleName()); } } public static void main(String[] args) { test("5", 1); test("five", 1); test("0", 1); test("2", 9); }}
Output
4
Not a number: five
Problem: ArithmeticException
Problem: ArrayIndexOutOfBoundsException
Only catch exceptions you can actually handle. Catch the most specific type you can. Never leave a catch block empty, or problems disappear silently. And let the rest bubble up.