gpt4 book ai didi

java - 在 Java 中抛出自定义异常

转载 作者:搜寻专家 更新时间:2023-10-30 19:50:00 24 4
gpt4 key购买 nike

为什么我需要在尝试抛出自定义异常时用 try/catch 包装我抛出的自定义异常,但对于一般异常我不必这样做?就像在示例中一样,我的 Exception 子类:

public class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}

抛出异常:

public class Exe {

private static void testex(String test) {
if (null!=test) {
throw new UnsupportedAddressTypeException();
} else {//Removing try/catch block results in compile failure
try {
throw new MyException("message");
} catch (MyException e) {
e.printStackTrace();
}
}
}
}

最佳答案

UnsupportedAddressTypeException 是 RuntimeException 的子类,来自 JavaDoc:

RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine.

A method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.

关于java - 在 Java 中抛出自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10574906/

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