Java 自定义异常

标签 java exception try-catch interrupted-exception

我想重现 InterruptedException 行为的一部分,但我不明白它是如何工作的......

所以我有这个代码:

public static void main(String [] args){
    try{
    }catch(InterruptedException ie){
    }
}

当我尝试编译它时,出现此编译器错误

Unreachable catch block for InterruptedException. This exception is never thrown from the try statement body

我创建了一个自定义异常,它并不是真正的异常,因为它没有扩展异常...

class MyException extends Throwable{
}
public static void main(String [] args){
    try{
    }catch(MyException ie){
    }
}

显示相同的编译器错误

Unreachable catch block for MyException. This exception is never thrown from the try statement body

然后我就这么做了

public static void main(String [] args){
    try{
        throw new MyException();
    } catch(MyException e){
        e.printStackTrace();
    }

    try{
        throw new InterruptedException();
    } catch(InterruptedException e){
        e.printStackTrace();
    }
}

它们都编译得很好。

但现在棘手的部分来了..

public static void main(String [] args){
    try{
        throw new MyException();
    } catch(Exception e){
        e.printStackTrace();
    } catch(MyException e){
        e.printStackTrace();
    }

    try{
        throw new InterruptedException();
    } catch(Exception e){
        e.printStackTrace();
    } catch(InterruptedException e){
        e.printStackTrace();
    }
}

编译器说

Unreachable catch block for InterruptedException. It is already handled by the catch block for Exception

你能告诉我 InterruptedException 如何显示“InterruptedException 无法访问的 catch block 。此异常永远不会从 try 语句主体中抛出”编译器错误并同时扩展 Exception,因为当我扩展异常时,我的自定义异常不会显示此编译器错误

举个例子:

class MyException extends Exception{}

public static void main(String [] args){
    try{        
    }catch(MyException me){     
    }
}

此代码不会引发任何编译器错误

但是下面的代码可以

class MyException extends Throwable{}

public static void main(String [] args){
    try{        
    }catch(MyException me){     
    }
}

最佳答案

发生这种情况是因为 InterrupedExceptionException 的子类,但 Exception 已被前面的 catch 捕获 block 。

Section 11.2.3 of the JLS状态:

It is a compile-time error if a catch clause can catch an exception class E1 and a preceding catch clause of the immediately enclosing try statement can catch E1 or a superclass of E1.

InterruptedException catch block 中的 block 将是无法访问的代码,这将是此编译器错误的原因。

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

相关文章:

java - 未抛出 MethodArgumentNotValidException

java - 直接从Array中删除元素

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

c# - 记录错误,然后将其打印出来

java - GUI 反序列化期间 Swing 触发监听器

c++ - 将 std::runtime_error 捕获为 std::exception 时出错

java - @Secured 抛出 AccessDeniedException 尽管角色是正确的

node.js - 我该如何处理服务器上的所有错误,使其永不崩溃?

java - Eclipse 不再检测丢失的 try/catch 吗?

java - 在 cassandra 中设置 TTL 后无法运行选择查询