gpt4 book ai didi

java - 如何在 Java 中获取特定类型的异常

转载 作者:行者123 更新时间:2023-12-04 02:30:14 25 4
gpt4 key购买 nike

我正在尝试获取一个特定的异常

输入H=-1;B=2;

预期输出

java.lang.Exception:宽度和高度必须为正值

电流输出

-2

public class Solution {
static int H,B;
static boolean flag = true;
static //static initializer block
{

Scanner sc = new Scanner(System.in);
H=sc.nextInt();
B=sc.nextInt();

}

public static void main(String[] args){
if(flag){
int area=B*H;
System.out.print(area);
}

}

}

我如何获得该特定异常?

最佳答案

你可以像这样抛出你自己的异常

if(H<0 || B<0){
throw new Exception("Breadth and height must be positive");
}

但是,最好为此使用 IllegalArgumentException 之类的东西。

if(H<0 || B<0){
throw new IllegalArgumentException("Breadth and height must be positive");
}

关于java - 如何在 Java 中获取特定类型的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64698625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com