我很困惑如何投掷和捕捉工作,我理解他们是这个ExceptionDemo的几个错误。如果有人能够解决这个错误并清楚地说明为什么以及如何在不使用所有Java术语的情况下纠正错误,并使用简单的术语 谢谢
public class ExceptionDemo {
public static void main( String [] args ) {
try {
int number = Integer.parseInt(”123”);
if (number > 100) {
catch new ArithmeticException(”Check the number”);
}
}
catch {
System.out.println(”Cannot convert to int”);
}
finally (Exception e) {
System.out.println(”Always print”);
}
}
}
答案 0 :(得分:1)
有点难以确切地说出这里需要什么。对于初学者看起来像在检查某种有效值时需要抛出异常。看起来像catch需要异常处理程序本身而不是finally。
//列出1个轻微的原创帖子
public class Main {
public static void main(String[] args) throws ArithmeticException {
try {
int number = Integer.parseInt("123");
if (number > 100) {
// is this what trying to do?
//would expect typically would be used to handle
//something like div by zero, etc.
throw new ArithmeticException("Check the number");
}
}
//catch exception(s) here
catch (Exception e) {
System.out.println("Cannot convert to int:" + e.toString());
}
finally {
System.out.println("Always print");
}
}
}
//列出2个更典型的东西
public class Main {
public static void main(String[] args) {
try {
//int number = Integer.parseInt("A123"); // if un-comment throws generic exception bad input
int number = 100 / 0; //will throw an "arithmetic" exception
//
if (number > 100) {
//do something.
int x = number++;
}
}
catch (ArithmeticException arithEx){
System.out.println("An ArithmeticException Occurred:" + arithEx.toString());
}
catch (Exception e) {
System.out.println("A general exception occurred:" + e.toString());
}
finally {
//always gets executed. so is good place to clean up, close connections etc.
System.out.println("Always print");
}
}
}
答案 1 :(得分:-1)
除了飓风的答案之外,你无法捕获新的例外。相反,你需要扔它。
throw new Exception();