练习-finally 接收两个整数(第一个为被除数,第二个为除数),实现以下需求: 1.求这两个数的商,并捕获除数为 0 的异常,捕获到该异常后输出提示语句:“除数不能为 0”; 2.不管是否捕获到异常,都输出给定两个数的和。
时间: 2024-09-11 15:03:37 浏览: 71
在Java中,你可以使用try-catch-finally结构来实现这个功能。finally块总是会被执行,无论是否抛出异常。下面是一个示例代码:
```java
public class DivisionPractice {
public static void main(String[] args) {
try {
int dividend = 10; // 被除数
int divisor = 0; // 除数
int result = divide(dividend, divisor);
System.out.println("商为:" + result);
} catch (ArithmeticException e) { // 捕获除数为0的ArithmeticException
System.out.println("除数不能为 0");
} finally {
int sum = dividend + divisor;
System.out.println("给定两个数的和为:" + sum);
}
}
public static int divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException(); // 如果除数为0,抛出异常
}
return a / b;
}
}
```
在这个例子中,`divide`方法会检查除数是否为零,如果为零则抛出`ArithmeticException`。在`main`方法中,我们尝试调用这个方法并处理可能的异常。不论是否发生异常,`finally`块都会执行并计算和输出两个数的和。
阅读全文
相关推荐


















