[英]Java static initializers
I'm learning java by working through some hacker rank problems.我正在通过解决一些黑客等级问题来学习 java。 The below code is about learning about static initializer block.下面的代码是关于学习 static 初始化块。 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输入:-1、2
expected output: java.lang.Exception: Breadth and height must be positive预期 output:java.lang.Exception:宽度和高度必须为正
actual output: Breadth and height must be positive -2 actual output:宽度和高度必须为正-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);
如果需要,您可以通过添加System.exit(1);
手动终止。
This code block catches your error and displays the message.此代码块捕获您的错误并显示消息。 In your case its "Breadth and height must be positive -2"在您的情况下,它的“宽度和高度必须为正 -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.移除 try catch。 Then you have to change Exception to RuntimeException然后你必须将 Exception 更改为 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:第二个选项的Output:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.