从键盘输入整数a,b,计算a/b,当b为0时,抛出自定义的异常java
时间: 2023-07-28 19:12:27 浏览: 100
代码如下:
```java
import java.util.Scanner;
public class Divide {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入被除数a:");
int a = sc.nextInt();
System.out.print("请输入除数b:");
int b = sc.nextInt();
try {
double result = divide(a, b);
System.out.println("结果为:" + result);
} catch (DivideByZeroException e) {
System.out.println(e.getMessage());
}
}
public static double divide(int a, int b) throws DivideByZeroException {
if (b == 0) {
throw new DivideByZeroException("除数不能为0!");
}
return (double) a / b;
}
}
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
```
运行截图如下:
```
请输入被除数a:10
请输入除数b:0
除数不能为0!
```
当输入的除数为0时,程序会抛出自定义的异常DivideByZeroException,并打印出异常信息。如果除数不为0,则正常计算并输出结果。
阅读全文