Java Static Initializer Block

  • + 0 comments
    // Static initialization block
    static {
        Scanner sc = new Scanner(System.in);
        try {
            // Reading input for breadth and height
            breadth = sc.nextInt();
            height = sc.nextInt();
    
            // Check if the values are positive
            if (breadth <= 0 || height <= 0) {
                // If either value is non-positive, set isValid to false
                isValid = false;
                // Throw an exception to handle the invalid case
                throw new Exception("Breadth and height must be positive");
            }
        } catch (Exception e) {
            // Handle the case where input values are invalid
            System.out.println("java.lang.Exception: Breadth and height must be positive");
            isValid = false;  // Mark as invalid
        }
    }
    
    public static void main(String[] args) {
        // If the values are valid, compute and print the area
        if (isValid) {
            int area = breadth * height;
            System.out.println(area);
        }
    }