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
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);