Intermediate Java Day 5: Exception Handling & Input Validation

Goal of this Day

Today you will learn:

By the end, you will be able to handle errors gracefully and validate user input safely.

Step 1: try-catch-finally

Use try to wrap code that might throw an exception.

Use catch to handle exceptions.

Use finally to run code regardless of whether an exception occurred.


Scanner sc = new Scanner(System.in);

try {
    System.out.print("Enter a number: ");
    int num = sc.nextInt();
    System.out.println("Number: " + num);
} catch(InputMismatchException e) {
    System.out.println("Invalid input!");
} finally {
    sc.close();
}

Step 2: Multiple catch Blocks

You can handle different types of exceptions separately.


try {
    int[] arr = {1, 2, 3};
    System.out.println(arr[5]); // may throw ArrayIndexOutOfBoundsException
} catch(InputMismatchException e) {
    System.out.println("Invalid input!");
} catch(ArrayIndexOutOfBoundsException e) {
    System.out.println("Index out of bounds!");
}

Step 3: Input Validation with Exceptions

Validate user input to ensure it meets criteria.


Scanner sc = new Scanner(System.in);
int number = -1;

while(number <= 0) {
    try {
        System.out.print("Enter a positive integer: ");
        number = sc.nextInt();

        if(number <= 0) {
            throw new IllegalArgumentException("Number must be positive!");
        }
    } catch(InputMismatchException e) {
        System.out.println("Invalid input! Enter a number.");
        sc.next(); // clear invalid input
    } catch(IllegalArgumentException e) {
        System.out.println(e.getMessage());
    }
}
System.out.println("You entered: " + number);
sc.close();

Step 4: Custom Exception Classes (Optional)

You can define your own exception classes.


class NegativeNumberException extends Exception {
    public NegativeNumberException(String message) {
        super(message);
    }
}

Practice


Scanner sc = new Scanner(System.in);
try {
    System.out.print("Enter a number: ");
    int num = sc.nextInt();
    System.out.println("Number: " + num);
} catch(InputMismatchException e) {
    System.out.println("Invalid input!");
} finally {
    sc.close();
}

Exercise

Create a program that only accepts positive integers from the user.

Steps:

Example:


import java.util.InputMismatchException;
import java.util.Scanner;

public class PositiveInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int number = -1;

        while(number <= 0) {
            try {
                System.out.print("Enter a positive integer: ");
                number = sc.nextInt();

                if(number <= 0) {
                    throw new IllegalArgumentException("Number must be positive!");
                }
            } catch(InputMismatchException e) {
                System.out.println("Invalid input! Enter a number.");
                sc.next(); // clear invalid input
            } catch(IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }

        System.out.println("You entered: " + number);
        sc.close();
    }
}