gpt4 book ai didi

java - 我如何编码可能发生的任何其他异常?

转载 作者:行者123 更新时间:2023-12-01 09:16:30 24 4
gpt4 key购买 nike

问题要求我定义两个异常:ZeroEnteredExceptionNegativeValueException。它们都有一个 private 变量来指示哪个值导致抛出异常。还为两者定义适当的构造函数。 “我怎样才能把构造函数放在这里?”

程序还必须处理可能发生的任何其他异常。根据需要使用适当的捕获 block 。 “我该如何使用可能发生的泡沫异常?”

import java.util.Scanner;

class ZeroEnteredException extends Exception {
public ZeroEnteredException(String s) {
super(s);
}
}

class NegativeValueException extends Exception {
public NegativeValueException(String s) {
super(s);
}
}

public class Question2 {


private static int q(int x ) throws ZeroEnteredException {
if ( x==0) throw new ZeroEnteredException(" Exception : the value is 0 ") ;
return x ;
}

private static int s(int n ) throws NegativeValueException {
if ( n < 0) throw new NegativeValueException(" Exception : the value is negative ") ;
return n ;
}

public static void main(String [] args) {
Scanner input = new Scanner(System.in) ;
int num ;
System.out.println(" enter a number : ") ;
while(true) {
num= input.nextInt();
try {
System.out.println(q(num) ) ;
System.out.println(s(num) ) ;

}catch(NegativeValueException o){
System.err.println(o.getMessage());
}catch(ZeroEnteredException e){
System.err.println(e.getMessage());
}

}
}
}

最佳答案

不确定我完全理解你的问题,如果没有,请告诉我不。

因此,首先,您需要向异常添加一个变量,该变量将包含引发异常的值以及访问该值的方法。就像这样:

class NegativeValueException extends Exception {
// This has to be private.
private int value;

//This will be the expected constructor
public NegativeValueException(String s, int value) {
super(s);
this.value = value;
}

// We need this to know the value which triggered the exception.
// We don't need to do it for the message because it already exists from the exception class.
public int getValue() {
return value;
}
}

完成后,您现在可以在引发异常时指定值:

throw new NegativeValueException("Exception : the value is negative", n) ;

最后,您可能想编写一个像这样的 try-catch block :

try {
// Some code that might throw your exceptions.
} catch (NegativeValueException e){
// You enter here when a NegativeValueException is thrown.
// This will display your exception message.
System.out.println(e.getMessage());
// This will display the number that threw the exception.
System.out.println(e.getValue());
} catch (ZeroEnteredException e) {
// You enter here when a ZeroEnteredException is thrown.
} catch (Exception e) {
// You enter here when an other exception is thrown.
e.printStackTrace();
}

旁注:不要忘记使用 catch block 从最具体的异常转到最通用的异常。因为一旦遇到符合异常类型的 catch block ,程序就会停止。这意味着,如果您将 catch (Exception e) 放在前面,它总是会出现在此处,而不会出现在任何其他 catch block 中,因为它是最通用的类​​型,并且所有异常都继承自 Exception。

关于java - 我如何编码可能发生的任何其他异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40513585/

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