如果方法抛出未在方法声明中使用“throws”指定的异常,会发生什么情况 [英] What happens if a method throws an exception that was not specified in the method declaration with "throws"

查看:981
本文介绍了如果方法抛出未在方法声明中使用“throws”指定的异常,会发生什么情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有使用过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?

推荐答案

Java有两种不同类型的例外:已检查例外和未选中例外。

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

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

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.

未经检查的异常的示例: IllegalArgumentException 有时用于通知已使用非法参数调用方法。不需要抛出。

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

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

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.

这篇关于如果方法抛出未在方法声明中使用“throws”指定的异常,会发生什么情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆