Java Exception Handling (Try-catch)

  • + 7 comments

    Again a great example of how bad the test cases are written. Any professional would have caught the exceptions together and logged / souted them in a uniform way like this:

    try (Scanner scanner = new Scanner(System.in)) {
    	System.out.println(scanner.nextInt()/scanner.nextInt());
    } catch (ArithmeticException | InputMismatchException ex) {
    	System.out.println(ex);
    } 
    

    This is best practise for any team I worked with and definitely the cleanest way to solve this. But thanks to the nitpicking test cases, beginners learn to catch exceptions in an utterly bloated way:

    try (Scanner scanner = new Scanner(System.in)) {
    	System.out.println(scanner.nextInt()/scanner.nextInt());
    } catch (ArithmeticException aex) {
    	System.out.println(aex);
    } catch (InputMismatchException imex) {
    	System.out.println(imex.getClass().getName());
    }