Java 自定义异常类每次都显示无法访问的 catch 块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22116175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:42:30  来源:igfitidea点击:

Custom Exception class shows Unreachable catch block everytime

javaexception

提问by collin

I've created a custom Exception class that I want to use in my application:

我创建了一个要在我的应用程序中使用的自定义 Exception 类:

public class MyException extends Exception {
    private static final long serialVersionUID = -2151515147355511072L;
    private String message = null;

    public MyException() {
        super();
    }

    public MyException(String message) {
        super(message);
        this.message = message;
    }

    public MyException(Throwable cause) {
        super(cause);
    }

    @Override
    public String toString() {
        return message;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

But when I try to use this class, like below, it gives a compile time error.

但是当我尝试使用这个类时,如下所示,它给出了一个编译时错误。

try {
    System.out.println("this");
} catch (MyException  e) {
    // TODO: handle exception
}

Compile time error:

编译时错误:

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

My question is if I'm extending Exception class & calling super in all constructors, then why this error is occurring?

我的问题是,如果我在所有构造函数中扩展 Exception 类并调用 super,那么为什么会发生此错误?

采纳答案by Hungry Blue Dev

Obviously, you are not doing anythingthat'd generate a MyException. First write a method with the signature throws MyException, call it and then your problem is solved. Here is an example:

显然,您没有做任何会生成MyException. 首先用签名写一个方法throws MyException,调用它,然后你的问题就解决了。下面是一个例子:

public void someMethod()throws MyException
{
    //some condition here.
    //if met..
    throw new MyException("cause");
}

and modify your main code as:

并将您的主要代码修改为:

try {
    someMethod();
    System.out.println("this");
} catch (MyException  e) {
    // TODO: handle exception
}

回答by ljgw

Can you try with:

你可以试试:

try {
    System.out.println("this");
    throw new MyException();
} catch (MyException  e) {
    // TODO: handle exception
}

Your exception wasn't thrown anywhere in the code. (try extending RuntimeExceptionas another option)

您的异常没有在代码中的任何地方抛出。(尝试扩展RuntimeException作为另一种选择)

回答by Karthik Kalyanasundaram

What the compile time error says is right "This exception is never thrown from the try statement body". You don't have anything which throws MyException

编译时错误所说的是正确的“这个异常永远不会从 try 语句体中抛出”。你没有任何东西可以抛出MyException

回答by sakura

The exception you created is a checked exception and must be thrown from somewhere to catch it. Any exception created by a java developer by extending Exceptionclass is a checked exception. And the rules applicable for checked exception will be applied on such exceptions.

您创建的异常是已检查的异常,必须从某个地方抛出才能捕获它。Java 开发人员通过扩展Exception类创建的任何异常都是已检查的异常。并且适用于检查异常的规则将应用于此类异常。

Another form of exception is called Unchecked Exception and usually created by extending RuntimeExceptionClass. A developer is free to catch such exception without an explicit need for throwing it somewhere from your code.

另一种异常形式称为 Unchecked Exception,通常通过扩展RuntimeExceptionClass创建。开发人员可以自由地捕获此类异常,而无需明确将其从代码中的某处抛出。

class Exception is also not thrown generally. I just want MyException behave like Exception.

class Exception 一般也不会抛出。我只希望 MyException 表现得像Exception.

This is what being further asked in one of the comments:

这是在其中一条评论中进一步提出的问题:

My take on this is you can think Exceptionclass as a large container which have many different and unique(to the point) child exceptions defined. And mostly these fine grained exceptions are thrown from Java Code. In a abstraction hierarchy, Exception is at higher level (not Highest as, Throwableis sitting there). Further, as a developer we all are always interested into the finer details like what kind of Exception is thrown. However, while handling exception, we sometimes write

我对此的看法是,您可以将Exception类视为一个大容器,其中定义了许多不同且独特的(就这一点而言)子异常。大多数这些细粒度的异常都是从 Java 代码中抛出的。在抽象层次结构中,异常处于更高级别(不是最高级别,Throwable而是坐在那里)。此外,作为开发人员,我们总是对更精细的细节感兴趣,例如抛出什么样的异常。然而,在处理异常时,我们有时会写

try{
   //some code lets assume throws IOException
    //Some code lets assume throws FileNotFoundException
 }
 catch (Exception ex) {
  //common handling which doesn't care if its IOException or FileNotFoundException
 }

You can not intervene in this exception hierarchy by just writing MyException extends Exception. By this what you are doing is your MyExceptionis a type of Exceptionnot itself Exceptionclass. So, you can't replace Exceptioncaught in catch with your MyException.

您不能仅通过编写MyException extends Exception. 通过这个,你正在做的是你MyException的类型Exception不是它本身的Exception类。所以,你不能Exception用你的MyException.