可能重复:
何时选择已检查和未检查的异常
你好!
所以,关于何时抛出已检查或未经检查的异常,我仍然感到很自在.我想知道其他人认为在这种情况下最合适的东西:
class Correlation<T>
{
private final T object1, object2;
private final double correlationCoefficient;
public Correlation(T object1, T object2, double correlationCoefficient)
{
if(Math.abs(correlationCoefficient) > 1.0 || (object1.equals(object2) && correlationCoefficient != 1.0))
throw new IllegalArgumentException();
this.object1 = object1;
this.object2 = object2;
this.correlationCoefficient = correlationCoefficient;
}
}
Run Code Online (Sandbox Code Playgroud)
因此,在这种情况下,我想抛出一个运行时异常,因为我无法从用户传入错误数据的情况中轻松恢复.我想事先指出我无法控制传入的数据.如果可以,我会创建一个接口,保证构造函数中的条件为真.但是,这是已经计算出的相关性的便利类,因此我必须相信用户正在提供准确的信息.
好的,让我知道你们的想法!
创建用户定义的异常时 最佳实践是什么,异常应创建为已检查还是未检查?
我知道不需要在代码中处理未经检查的/运行时异常。
我发现Java的反射API是异常冗长的,我经常想要捕获每个特定的异常,但只是抛出异常.这是不好的做法,还是你真的把所有这些例外都抛在了方法签名上?然后,调用该方法的每个方法都必须以某种方式处理每个特定的异常.相反,我正在考虑这样做:
public void someMethod()
throws Exception {
try {
// do a bunch of reflection...
} catch(ClassCastException classCastException) {
throw new Exception("Some specific message.", classCastException);
} catch(InvocationTargetException invocationTargetException) {
throw new Exception("Some specific message.", invocationTargetException);
}
}
Run Code Online (Sandbox Code Playgroud)
这种做法很糟糕吗?
当变量 d1 和 d2 不是正确的数据类型时,我总是收到默认的 NumberFormatException 消息。
当使用 throw 语句条件捕获这些异常时,我想打印我的自定义异常消息。
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a numeric value: ");
String input1 = sc.nextLine();
Double d1 = Double.parseDouble(input1);
System.out.print("Enter a numeric value: ");
String input2 = sc.nextLine();
Double d2 = Double.parseDouble(input2);
System.out.print("Choose an operation (+ - * /): ");
String input3 = sc.nextLine();
try {
if (!(d1 instanceof Double)) {
throw (new Exception("Number formatting exception caused by: "+d1));
}
if (!(d2 instanceof Double)) { …Run Code Online (Sandbox Code Playgroud)