Java 中异常的 throws 关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1989077/
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 02:09:24  来源:igfitidea点击:

The throws keyword for exceptions in Java

javaexception

提问by mrblah

when you do this:

当你这样做时:

public class Blah {

    public void doBlah() throws BlahException {

    }

}

What does adding the throws BlahExceptionreally do?

添加throws BlahException真正的作用是什么?

Does it basically group any exception to that one? i.e. if there is an exception, no matter what it is, will always be thrown using BlahException?

它是否基本上将任何例外归为一类?即如果有异常,不管它是什么,总是会被抛出使用BlahException?

回答by duffymo

It tells the clients of your class that the DoBlah method can throw a BlahException or any other exception that extends it.

它告诉您的类的客户 DoBlah 方法可以抛出 BlahException 或扩展它的任何其他异常

If it's a checked exception, the compiler will require that they wrap calls to this method in a try/catch block. If it's unchecked, they can choose to not catch the exception, but they have to be aware that if they don't it'll be bubbled further up the call stack.

如果它是已检查的异常,编译器将要求他们将此方法的调用包装在 try/catch 块中。如果未选中,他们可以选择不捕获异常,但他们必须注意,如果不这样做,它将在调用堆栈中进一步向上冒泡。

It doesn't say anything about unchecked exceptions like NullPointException or errors. Those can always be thrown as well. They aren't required in the throws clause.

它没有说明诸如 NullPointException 或错误之类的未经检查的异常。那些也总是可以抛出的。throws 子句中不需要它们。

This code shows how it works:

这段代码展示了它是如何工作的:

ExceptionDemo.java:

异常Demo.java:

package exceptions;

public class ExceptionDemo
{
    public static void main(String[] args)
    {
        ExceptionDemo demo = new ExceptionDemo();

        try
        {
            // Removing the try/catch will result in a compilation error
            demo.doChecked();            
        }
        catch (CheckedException e)
        {
            e.printStackTrace();
        }

        // Note: Not inside a try/catch, in spite of the throws clause
        demo.doUnchecked();
    }

    public void doChecked() throws CheckedException
    {
        System.out.println("doing something that may throw a checked exception");
    }

    // Note: "throws" clause is unnecessary for an unchecked exception
    public void doUnchecked() throws UncheckedException
    {
        System.out.println("doing something that may throw an unchecked exception");
    }
}

CheckedException.java:

检查异常.java:

package exceptions;

public class CheckedException extends Exception
{
    public CheckedException()
    {
        super();
    }

    public CheckedException(String message)
    {
        super(message);
    }

    public CheckedException(String message, Throwable cause)
    {
        super(message, cause);
    }

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

UncheckedException.java:

UncheckedException.java:

package exceptions;

public class UncheckedException extends RuntimeException
{
    public UncheckedException()
    {
        super();
    }

    public UncheckedException(String message)
    {
        super(message);
    }

    public UncheckedException(String message, Throwable cause)
    {
        super(message, cause);
    }

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

回答by Chinmay Kanchi

No. the throws BlahExceptionclause tells the compiler that your function mightthrow a BlahException and that this should be caught by the caller. For example:

不。该throws BlahException子句告诉编译器您的函数可能会抛出 BlahException 并且这应该被调用者捕获。例如:

class ExceptionThrower
{
    void someFunction()
    {
        for(int i =0; i<10;i++)
            if(i==4) throw new Exception();
    }

    public static void main(String args[])
    {
        new ExceptionThrower().someFunction();
    }
}

This program will not compile, because it can throw an exception of type Exception, and the exception has neither been caught nor declared to be thrown.

该程序将无法编译,因为它可以抛出类型Exception为 的异常,并且该异常既没有被捕获也没有声明要抛出。

However, the following code will compile fine.

但是,以下代码可以正常编译。

class ExceptionThrower
{
    void someFunction() throws Exception
    {
        for(int i =0; i<10;i++)
            if(i==4) throw new Exception();
    }

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

    }
}

Essentially, you are telling the compiler that this function mightthrow an Exception that is not handled inside the function itself. These types of exceptions are all subclasses of java.lang.Exceptionand are called checked exceptions. Other exceptions that indicate a catastrophic failure caused by bugs in the program itself, rather than by a condition such as malformed input are subclasses of java.lang.RuntimeExceptionand these are called unchecked exceptions. In short, unchecked exceptions can be thrown without a throwsclause in the method signature, while any checked exceptions must be indicated there.

本质上,您是在告诉编译器该函数可能会抛出一个未在函数本身内部处理的异常。这些类型的异常都是java.lang.Exception检查异常的子类。其他指示由程序本身的错误而不是格式错误等条件引起的灾难性故障的异常是 的子类,java.lang.RuntimeException这些异常称为unchecked exceptions。简而言之,未经检查的异常可以throws在方法签名中没有子句的情况下抛出,而任何已检查的异常都必须在那里指出。

For a discussion of checked vs. unchecked exceptions see http://www.javapractices.com/topic/TopicAction.do?Id=129

有关已检查与未检查异常的讨论,请参阅http://www.javapractices.com/topic/TopicAction.do?Id=129

回答by fastcodejava

Your method doBlah()need to have something that can throwBlahExceptionor any subclass of BlahException. This tells caller of doBlah()to be careful usually to wrap the code in try-catch.

您的方法doBlah()需要具有可以throwBlahException或任何子类的东西BlahException。这告诉调用者doBlah()通常要小心将代码包装在try-catch.

回答by TheJoker

The whole idea is that without throwskeyword, the exception raised by the method cannot be handled outside the method.

整个想法是,没有throws关键字,方法引发的异常无法在方法外处理。

Isn't it so?

不是这样吗?