给这段代码增加详细注释import java.util.Scanner;// 自定义除数为0的异常类class DivideByZeroException extends Exception { public DivideByZeroException(String message) { super(message); }}public class CustomExceptionDemo { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); try { System.out.print("请输入被除数:"); double dividend = Double.parseDouble(scanner.nextLine()); System.out.print("请输入除数:"); double divisor = Double.parseDouble(scanner.nextLine()); if (divisor == 0) { throw new DivideByZeroException("除数不能为0"); } System.out.println("结果为:" + (dividend / divisor)); } catch (NumberFormatException e) { System.out.println("数字格式异常:" + e.getMessage()); } catch (DivideByZeroException e) { System.out.println("自定义异常:" + e.getMessage()); } catch (Exception e) { System.out.println("通用型异常:" + e.getMessage()); } }}
时间: 2024-03-07 14:51:09 浏览: 21
// 导入 Scanner 类用于读取用户输入
import java.util.Scanner;
// 自定义除数为0的异常类
class DivideByZeroException extends Exception {
public DivideByZeroException(String message) {
super(message);
}
}
public class CustomExceptionDemo {
public static void main(String[] args) {
// 创建一个 Scanner 对象,用于读取用户输入
Scanner scanner = new Scanner(System.in);
try {
System.out.print("请输入被除数:");
// 读取用户输入的被除数
double dividend = Double.parseDouble(scanner.nextLine());
System.out.print("请输入除数:");
// 读取用户输入的除数
double divisor = Double.parseDouble(scanner.nextLine());
// 如果除数为0,则抛出自定义异常
if (divisor == 0) {
throw new DivideByZeroException("除数不能为0");
}
// 计算结果并输出
System.out.println("结果为:" + (dividend / divisor));
} catch (NumberFormatException e) {
// 如果用户输入的数字格式不正确,则捕获该异常并提示用户
System.out.println("数字格式异常:" + e.getMessage());
} catch (DivideByZeroException e) {
// 如果除数为0,则捕获自定义异常并提示用户
System.out.println("自定义异常:" + e.getMessage());
} catch (Exception e) {
// 捕获其他未知异常并提示用户
System.out.println("通用型异常:" + e.getMessage());
}
}
}