如果方法抛出未在方法声明中用“throws”指定的异常,会发生什么情况?

发布于 2024-10-16 06:48:09 字数 105 浏览 2 评论 0原文

我从来没有使用过“throws”子句,今天一位伙伴告诉我,我必须在方法声明中指定该方法可能抛出哪些异常。然而,我一直在使用异常,没有任何问题,但没有这样做,那么,如果实际上需要它,为什么需要它呢?

I've never used the "throws" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I've been using exceptions without problems without doing it, so, why is it needed if, in fact, it's needed?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

雪若未夕 2024-10-23 06:48:09

Java 有两种不同类型的异常:已检查异常和未检查异常。

未经检查的异常是 RuntimeException 的子类,您不必添加 throws 声明。所有其他异常都必须在方法主体中处理,可以使用 try/catch 语句或使用 throws 声明。

未检查异常的示例:IllegalArgumentException 有时用于通知已使用非法参数调用了方法。无需投掷。

检查异常的示例:java.io 包中的某些方法可能会抛出的 IOException。使用 try/catch 或将 throws IOException 添加到方法声明中,并将异常处理委托给方法调用者。

Java has two different types of exceptions: checked Exceptions and unchecked Exceptions.

Unchecked exceptions are subclasses of RuntimeException and you don't have to add a throws declaration. All other exceptions have to be handled in the method body, either with a try/catch statement or with a throws declaration.

Example for unchecked exceptions: IllegalArgumentException that is used sometimes to notify, that a method has been called with illegal arguments. No throws needed.

Example for checked exceptions: IOException that some methods from the java.io package might throw. Either use a try/catch or add throws IOException to the method declaration and delegate exception handling to the method caller.

自此以后,行同陌路 2024-10-23 06:48:09

如果使用 throws 关键字声明一个方法,则希望调用该方法的任何其他方法必须准备好捕获它,或者声明本身将抛出异常。

例如,如果您想暂停应用程序,则必须调用 Thread.sleep(milliseconds); ,

但此方法的声明表明它将抛出 InterruptedException

异常:

public static void sleep(long millis) throws InterruptedException

因此,如果您希望在 main 方法中调用它,则必须捕获它:

public static void main(String args[]) {
    try {
        Thread.sleep(1000);
    } catch(InterruptedException ie) {
        System.out.println("Opps!");
    }
}

或者让该方法也声明它抛出异常:

public static void main(String args[]) throws InterruptedException {
    Thread.sleep(1000);
}

If a method is declared with the throws keyword then any other method that wishes to call that method must either be prepared to catch it or declare that itself will throw an exception.

For instance if you want to pause the application you must call Thread.sleep(milliseconds);

But the declaration for this method says that it will throw an InterruptedException

Declaration:

public static void sleep(long millis) throws InterruptedException

So if you wish to call it for instance in your main method you must either catch it:

public static void main(String args[]) {
    try {
        Thread.sleep(1000);
    } catch(InterruptedException ie) {
        System.out.println("Opps!");
    }
}

Or make the method also declare that it is throwing an exception:

public static void main(String args[]) throws InterruptedException {
    Thread.sleep(1000);
}
守望孤独 2024-10-23 06:48:09

即使存在已检查异常,这种情况也可能发生。有时它会破坏日志记录。

假设一个库方法使用此技巧来允许实现可以抛出 IOException 的 Runnable :

class SneakyThrowTask implements Runnable {

    public void run() {
        throwSneakily(new IOException());
    }

    private static RuntimeException throwSneakily(Throwable ex) {
        return unsafeCastAndRethrow(ex);
    }

    @SuppressWarnings("unchecked")
    private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
        throw (X) ex;
    }

}

并且您可以这样调用它:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    }
}

异常将永远不会被记录。因为它是一个受检查的异常,所以你不能这样写:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    } catch (IOException ex) {
        LOGGER.log(ex); // Error: unreachable code
    }
}

It can happen, even with checked exceptions. And sometimes it can break logging.

Suppose a library method uses this trick to allow an implementation of Runnable that can throw IOException:

class SneakyThrowTask implements Runnable {

    public void run() {
        throwSneakily(new IOException());
    }

    private static RuntimeException throwSneakily(Throwable ex) {
        return unsafeCastAndRethrow(ex);
    }

    @SuppressWarnings("unchecked")
    private static <X extends Throwable>X unsafeCastAndRethrow(Throwable ex) throws X {
        throw (X) ex;
    }

}

And you call it like this:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    }
}

The exception will never be logged. And because it's a checked exception you cannot write this:

public static void main(String[] args) {
    try {
        new SneakyThrowTask().run();
    } catch (RuntimeException ex) {
        LOGGER.log(ex);
    } catch (IOException ex) {
        LOGGER.log(ex); // Error: unreachable code
    }
}
情深已缘浅 2024-10-23 06:48:09
  1. 您需要声明您的方法抛出的已检查异常。
  2. 如果您声明“抛出异常”,它几乎涵盖了大多数(如果不是全部)检查异常,那么
  3. 您始终可以抛出未经检查的运行时异常,而不必声明。

我非常确定,如果您尝试抛出已检查的异常,并且尚未将方法声明为抛出该类型,则代码甚至不会编译(现在检查)。

编辑,对,所以如果你尝试一些简单的事情,比如

public static void main(String[] args) {
   throw new Exception("bad");
}

你会得到一个编译错误。

具体来说,对于您的问题,如果您调用声明为抛出异常的方法,您必须尝试/捕获该方法调用,或者声明您的方法抛出异常。

  1. You need to declare checked exceptions that your method throws.
  2. If you declare 'throws Exception' that pretty much covers most if not all checked exceptions
  3. You can always throw an unchecked runtime exception and not have to declare.

Im pretty sure if you try to throw a checked exception, and haven't declared the method as throwing that type, the code wont even compile (checking now).

EDIT, right so if you try something simple like

public static void main(String[] args) {
   throw new Exception("bad");
}

you get a compile error.

Specifically for your question, if you invoke a method that is declared to throw Exception(s) you must either try/catch the method invocation, or declare that your method throws the exceptions.

灼痛 2024-10-23 06:48:09

throws 关键字用于向另一个方法抛出异常。

它减轻了用户处理异常的负担。因为这样所有的异常都可以在用于运行的方法中处理。

大多数情况下它主要是一个方法,这样用户就不需要在方法内部探索。

它还向编译器抛出关键字force来处理可能发生的异常。

如果您是 API 开发人员,当您编写代码时,您可能会发现可能会发生异常,因此您可以在方法运行时使用 throws 关键字来处理它。

The throws key word is used to throw an exception to another method.

It eases the handle exception to the user. Because then all of the exceptions can be handled in a method which is used to run.

Mostly it is mainly a method, so that the user does not need to explore inside the method.

It also throws keyword force to the compiler to handle the exception which could be occurring.

If you were a API developer, when you write a code, you might see that an exception could occur, so you use the throws keyword to handle it when the method runs.

禾厶谷欠 2024-10-23 06:48:09

Java throws 关键字,

  • Java throws 关键字用于声明异常。
  • throws 后面是类。
  • 检查异常可以通过抛出来传播。
  • 它向方法的调用者提供有关异常的信息。

抛出示例,

void m()throws ArithmeticException{  
    //method code  
}  

Java throws keyword,

  • Java throws keyword is used to declare an exception.
  • throws is followed by class.
  • Checked exception can be propagated with throws.
  • It provides information to the caller of the method about the exception.

throws example,

void m()throws ArithmeticException{  
    //method code  
}  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文