简体   繁体   English

Java 抛出异常(不是类转换异常)

[英]Java casting an exception (not class cast exception)

When an exception is caught in java is there a use case for casting the exception to a new type?当在 java 中捕获异常时,是否有将异常转换为新类型的用例? Or is the standard或者是标准

    throw new DiffException(e)

The only way to do it.做到这一点的唯一方法。 I apologize if I'm overlooking something but the only search results I get are for "ClassCastExceptions" Which is obviously not what I'm looking for如果我忽略了一些东西,我很抱歉,但我得到的唯一搜索结果是“ClassCastExceptions”,这显然不是我要找的

I believe you meant 'exception wrapping' .我相信你的意思是'exception wrapping' There's no other way to do it - you create a new instance of Exception using a constructor which takes another exception as cause.没有其他方法可以做到这一点 - 您使用构造函数创建一个新的Exception实例,该构造函数将另一个异常作为原因。 This works thanks to 1-arg constructor of java.lang.Exception .这要归功于java.lang.Exception 的 1-arg 构造函数 The typical implementation of custom exception type (like your DiffException ) declares such 1-arg constructor too.自定义异常类型的典型实现(如您的DiffException )也声明了这样的 1-arg 构造函数。

Well, if the exception caught ( e in your case I suppose) is a subtype of DiffException , you could of course cast it like好吧,如果赶上(例外e你的情况我想)是的一个亚型DiffException ,你当然可以它像

throw (DiffException) e;

but I doubt that's what you want to do, since it doesn't make a difference (the e will still have the same runtime type, even in the receiving end).但我怀疑这就是您想要做的,因为它没有任何区别(即使在接收端, e仍将具有相同的运行时类型)。

So the answer is most likely, no , there is no other, equivalent way, of doing所以答案很可能是,,没有其他等效的方式来做

throw new DiffException(e);

than doing just that.而不是这样做。

It should be noted however, that doing new DiffException(e) is not called casting but, wrapping , or chaining the exception.然而,应该注意的是,执行new DiffException(e)不称为强制转换,而是,包装链接异常。

Since you mentioned use cases, the common one in Java is wrapping a checked exception as unchecked;既然您提到了用例,Java 中的常见用例就是将已检查的异常包装为未检查的; this is appropriate when there's no way the checked exception can occur, such as here:当检查异常不可能发生时,这是合适的,例如:

public static Reader getUTF8Reader(InputStream is) {
    try {
        return new InputStreamReader(inputStream, "UTF-8");
    } catch(UnsupportedEncodingException e) {
        // should never happen since UTF-8 is guaranteed to be available as per
        // http://download.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html
        throw new RuntimeException("UTF-8 not available", e);
    }
}

Without wrapping the exception, you'd either have to swallow it (which feels wrong) or declare the method as throws UnsupportedEncodingException which forces anyone using it to catch the exception that will never be thrown .如果不包装异常,您要么不得不吞下它(这感觉不对),要么将该方法声明为throws UnsupportedEncodingException ,这会强制任何使用它的人捕获永远不会抛出的异常 Wrapping it, there's no onus on the caller to handle unlikely cases, yet we're protected in the unlikely event that UTF-8 isn't available on some obscure platform in the future.包装它,调用者没有责任处理不太可能的情况,但我们受到保护,以防万一将来某个晦涩的平台上无法使用 UTF-8。

If I understand you correctly here is the use case I am thinking about.如果我理解正确,这里就是我正在考虑的用例。 expression:表达:

new FileInputStream("the path");

may throw FileNotFoundException if the file does not exist.如果文件不存在,则可能抛出FileNotFoundException FileNotFoundException extends IOException , so you could write code like: FileNotFoundException扩展了IOException ,因此您可以编写如下代码:

public void readFromFile(String path) {
    InputStream in = new FileInputStream(path);
    // do something....
}

Now you can call this method as following:现在您可以按如下方式调用此方法:

try {
    readFromFile("myFile");
} catch (IOException e) {
    if (e instanceof FileNotFoundException) {
        FileNotFoundException fnfe = (FileNotFoundException)e;
        // do something
    }
    // do something else
}

But I'd recommend you create separate catch blocks for FileNotFoundException and for IOException (at least for this use-case):但我建议您为FileNotFoundExceptionIOException创建单独的 catch 块(至少对于这个用例):

try {
    readFromFile("myFile");
} catch (FileNotFoundException e) {
    // do something with FileNotFoundException
} catch (IOException e) {
    // do something with IOException
}

This code does not contain instanceof, casting and other ugly stuff.这段代码不包含 instanceof、casting 和其他丑陋的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM