Java 创建自定义异常
我正在尝试创建一个方法Java 创建自定义异常,java,exception-handling,throws,Java,Exception Handling,Throws,我正在尝试创建一个方法f1(x),当x等于5时抛出异常。之后,我将尝试从另一个方法调用该方法f2(),以调用该异常。然后我必须调用f1(x+1)来恢复f2()。我试着编写代码,但我被卡住了。代码如下: public class FiveException extends Exception { public void f1(int x) throws FiveException { if (x == 5) { throw new FiveException();
f1(x)
,当x等于5时抛出异常。之后,我将尝试从另一个方法调用该方法f2()
,以调用该异常。然后我必须调用f1(x+1)
来恢复f2()。我试着编写代码,但我被卡住了。代码如下:
public class FiveException extends Exception {
public void f1(int x) throws FiveException {
if (x == 5) {
throw new FiveException();
}
}
public void f2() {
int x = 5;
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
}
}
public static void main(String[] args) {
FiveException x5 = new FiveException();
x5.f2();
}
}
print语句可以工作,但我不确定如何调用f(x+1)
。感谢您提供有关如何修复此问题以及编写异常的任何技术的帮助。因为f1
抛出FiveException
,无论您在哪里调用f1
,您都必须捕获异常或将其抛出到调用引发异常的方法的方法。例如:
public static void main(String[] args) throws FiveException {
FiveException x5 = new FiveException();
x5.f1(1);
}
或:
但是你的代码很混乱。。。通常,抛出自身的不是异常类,而是其他类抛出异常类
如果在catch语句中调用它,则必须用另一个try catch
,因为catch
中的代码不受保护,如下所示:
public void f2() {
int x = 5;
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
try {
f1(x + 1);
} catch (FiveException e) {
e.printStackTrace();
}
}
}
但这段代码很难看,您可以编写以下代码:
public void f2() {
int x = 5;
fProtected(x);
fProtected(x + 1);
}
private void fProtected(int x) {
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
}
}
引发异常的代码不应在FiveException类中。要在何处调用f1(x+1)
?在哪个方法中?@fhelvanger我尝试在f2()
中的catch语句下调用f1(x+1)
,但它给了我一个错误。很有趣。我会研究一下,看看这是否是我想要的代码。
public void f2() {
int x = 5;
fProtected(x);
fProtected(x + 1);
}
private void fProtected(int x) {
try {
f1(x);
}catch (FiveException e) {
System.out.println("x is 5");
}
}