Java: When is a static initialization block useful?

前端 未结 13 1609
时光说笑
时光说笑 2020-11-30 16:49

What\'s the difference between initialization within a static block:

public class staticTest {

    sta         


        
相关标签:
13条回答
  • 2020-11-30 17:25

    You can use try/catch block inside static{} like below:

    MyCode{
    
        static Scanner input = new Scanner(System.in);
        static boolean flag = true;
        static int B = input.nextInt();
        static int H = input.nextInt();
    
        static{
            try{
                if(B <= 0 || H <= 0){
                    flag = false;
                    throw new Exception("Breadth and height must be positive");
                }
            }catch(Exception e){
                System.out.println(e);
            }
    
        }
    }
    

    PS: Referred from this!

    0 讨论(0)
提交回复
热议问题