Java 如何最好地检测某些异常?

Java 如何最好地检测某些异常?,java,exception,try-catch,Java,Exception,Try Catch,首先:StackOverflow告诉我这个问题是主观的,而事实并非如此 我有以下代码: try { // Some I/O code that should work fine, but might go weird // when the programmer fails or other stuff happens... // It will also throw exceptions that are completely fine, // such as

首先:StackOverflow告诉我这个问题是主观的,而事实并非如此

我有以下代码:

try {
    // Some I/O code that should work fine, but might go weird
    // when the programmer fails or other stuff happens...
    // It will also throw exceptions that are completely fine,
    // such as when the socket is closed and we try to read, etc.
} catch (Exception ex) {
    String msg = ex.getMessage();
    if (msg != null) {
        msg = msg.toLowerCase();
    }
    if (msg == null || (!msg.equals("pipe closed") &&
                !msg.equals("end of stream reached") &&
                !msg.equals("stream closed") &&
                !msg.equals("connection reset") &&
                !msg.equals("socket closed"))) {
        // only handle (log etc) exceptions that we did not expect
        onUnusualException(ex);
    }
    throw ex;
}
正如您所看到的,我检查某些异常的过程是有效的,但是非常脏。我担心某些VM可能会对不应导致调用指定方法的异常使用其他字符串


对于这个问题,我可以使用哪些不同的解决方案?如果我使用
IOException
检查非异常(lol)异常,我将不会捕获任何从它派生或使用它的异常。

对于扩展
IOException
的异常(或另一个异常),将其放在扩展的异常之前的单独的
catch
语句中

try {
    // this might throw exceptions
} catch (FileNotFoundException e) { // this extends IOException
    // code
} catch (IOException e) {
    // more code
}
在上面的示例中,如果异常是
FileNotFoundException
的实例,则将执行第一条语句中的代码。仅当第二个异常是
IOException
而不是
FileNotFoundException
时,才会执行第二个异常。使用这种方法,您可以处理多个相互扩展的异常类型。
您还可以在同一
catch
语句中捕获多种类型的异常

try {
    // even more code
} catch (IOException|ArithmeticException e) {
    // this will run if an IOException or ArithmeticException is thrown
}

希望这有帮助。

谢谢!虽然这可能是一个更好的解决方案的一部分,但它并不完全是我所需要的。例如,我可能碰巧捕获到一个
NullPointerException
或任何其他异常,这些异常是由糟糕的编程引起的,但对于某些特定的异常,我知道它们将由于所使用函数的工作方式而发生。我不能对可能抛出的异常做出任何假设——如果一切正常,无论如何都不应该调用代码。我只能说,
有些例外是可以预料到的,而所有其他例外都不是
IOException
仅用于某些预期的异常。