Home > database >  Java static initializers
Java static initializers

Time:04-09

I'm learning java by working through some hacker rank problems. The below code is about learning about static initializer block. The exception is thown and caught but the program keeps running and I am uncertain why.

java

    import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

//Write your code here
    public static int B;
    public static int H;
    public static boolean flag;
    public static  Scanner sc;
    
    static {
        try{
            sc = new Scanner(System.in);
        flag = true;
         B = sc.nextInt();
            H = sc.nextInt();
        
        if(B < 0 || H < 0){
            throw new Exception("Breadth and height must be positive");
        } 
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    
    
public static void main(String[] args){
        if(flag){
            int area=B*H;
            System.out.print(area);
        }
        
    }//end of main

}//end of class

input: -1, 2

expected output: java.lang.Exception: Breadth and height must be positive

actual output: Breadth and height must be positive -2

CodePudding user response:

The exception is caught correctly so there is no reason to terminate the program. If you want, you can terminate manually anyway by adding System.exit(1);

CodePudding user response:

This code block catches your error and displays the message. In your case its "Breadth and height must be positive -2"

}catch (Exception e){
    System.out.println(e.getMessage());
}

This will fix it:

}catch (Exception e){
    System.out.println(e.getMessage());
    System.exit(1);
}

However you should be doing this:
Remove the try catch. Then you have to change Exception to RuntimeException

static {
        sc = new Scanner(System.in);
        flag = true;
        B = sc.nextInt();
        H = sc.nextInt();

        if (B < 0 || H < 0) {
            throw new RuntimeException("Breadth and height must be positive");
        }

    }

Output of the 2nd option:

1
-2
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.RuntimeException: Breadth and height must be positive
    at Main.<clinit>(Main.java:18)
  • Related