下面程序的运行结果是( ) public class Demo { public static void main(String[] args) { try { System.out.println(10 / 0); } catch (RuntimeException e) { System.out.println("RuntimeException"); } catch (ArithmeticException e) { System.out.println("ArithmeticException"); } } }
时间: 2024-02-14 16:32:58 浏览: 24
答案是 "ArithmeticException"。在代码中,我们首先抛出了一个算术异常,然后在catch块中捕获它。因为ArithmeticException是RuntimeException的子类,所以我们必须首先匹配ArithmeticException处理程序,否则它将被RuntimeException处理程序捕获。因此,程序将打印出"ArithmeticException"。
相关问题
class Main { static void procedure() throws IllegalAccessException { System.out.println("inside procedure"); IllegalAccessException("demo"); } public static void main(String args[]) { try { procedure(); } catch ( ) { System.out.println("捕获:" + e); } } }
这段代码有一些问题,比如:
1. 在 `IllegalAccessException` 抛出的地方缺少 `new` 关键字,应该是 `new IllegalAccessException("demo")`。
2. 在 `catch` 块中缺少异常类型,应该是 `catch (IllegalAccessException e)`。
3. 缺少异常处理的代码,应该在 `catch` 块中加入处理异常的代码,比如输出异常信息或者进行其他处理。
改正后的代码如下:
```
class Main {
static void procedure() throws IllegalAccessException {
System.out.println("inside procedure");
throw new IllegalAccessException("demo");
}
public static void main(String args[]) {
try {
procedure();
} catch (IllegalAccessException e) {
System.out.println("捕获:" + e);
}
}
}
```
public class Demo { public static void main(String[] args) { int num = 10; System.out.println(test (num)) ; 7 public static int test (int b) { try { b += 10; return b; } catch (RuntimeException e) { } catch (Exception e2) { ] finally { b += 10; return b; } }
这段代码是有问题的,编译器会提示错误信息。
首先,在test方法中,try和catch语句块都没有返回语句,因此编译器会提示缺少返回语句的错误。另外,在finally语句块中也有一个返回语句,这样会导致try或catch语句块中的返回语句被忽略,因为finally语句块中的返回语句会覆盖try或catch语句块中的返回语句。
因此,如果想要修复这段代码,需要在finally语句块中移除返回语句,或者在try或catch语句块中添加一个返回语句。例如,可以将finally语句块中的return b;改为b += 10;。
修复后的代码如下:
public class Demo {
public static void main(String[] args) {
int num = 10;
System.out.println(test(num));
}
public static int test(int b) {
try {
b += 10;
return b;
} catch (RuntimeException e) {
} catch (Exception e2) {
} finally {
b += 10;
}
return b;
}
}
这样,输出结果为30。