Classify Input Errors

medium Exception Handling

Problem

Each input line has two tokens a and b. Print the integer quotient a / b (cut toward zero). If a token is not a whole number (it may start with + or -, no decimal point), print bad number. If b is 0, print division by zero. Check the numbers first, then the zero. Use separate catch blocks for the two kinds of error.

Constraints

  • 1 <= lines <= 10^4

Examples

Input

10 2
7 0
x 3

Output

5
division by zero
bad number

Solutions

Best approachTime O(n)Space O(n)

Order matters: the numbers are parsed before the division, so a bad number is reported even when b is 0. Python's int() accepts a few more forms than Java (for example underscores), but the inputs here avoid them. Catch the most specific exception, not a general Exception, so unrelated bugs are not hidden.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process lines.
 * Input   : Several lines.
 * Output  : One answer per line.
 * Approach: Separate catch blocks.
 * Time    : O(n)
 * Space   : O(n)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static String[] solve(String[] lines) {
        String[] output = new String[lines.length];
        for (int i = 0; i < lines.length; i++) {
            String[] part = lines[i].split(" ");

            // Step 1: Two different problems can happen in the same try block. Each has its own catch block.
            try {
                long first = Long.parseLong(part[0]);
                long second = Long.parseLong(part[1]);
                output[i] = String.valueOf(first / second);
            } catch (NumberFormatException error) {
                // Step 2: parseLong throws NumberFormatException for text like "x" or "1.5".
                output[i] = "bad number";
            } catch (ArithmeticException error) {
                // Step 3: Dividing a long by zero throws ArithmeticException.
                output[i] = "division by zero";
            }
        }
        return output;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        java.util.List<String> all = new java.util.ArrayList<>();
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine().trim();
            if (!line.isEmpty()) {
                all.add(line);
            }
        }
        String[] lines = all.toArray(new String[0]);
        System.out.println(String.join("\n", solve(lines)));
    }
}
Hints (1)
  1. Why is catching Exception for everything a bad idea?