Java 异常处理:throw、throws 和 Throwable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3940213/
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
Exception handling : throw, throws and Throwable
提问by Sumithra
Can any of you explain what the differences are between throw
, throws
and Throwable
and when to use which?
可以任你解释的区别是什么之间throw
,throws
以及Throwable
和什么时候使用?
采纳答案by aioobe
throws
: Used when writing methods, to declare that the method in question throws the specified (checked) exception.As opposed to checked exceptions, runtime exceptions (NullPointerExceptions etc) may be thrown without having the method declare
throws NullPointerException
.throw
: Instruction to actually throw the exception. (Or more specifically, the Throwable).The throw keyword is followed by a reference to a
Throwable
(usually an exception).
throws
:在编写方法时使用,用于声明所讨论的方法抛出指定的(已检查的)异常。与检查异常相反,运行时异常(NullPointerExceptions 等)可能会在没有方法 declare 的情况下被抛出
throws NullPointerException
。throw
: 实际抛出异常的指令。(或者更具体地说,Throwable)。throw 关键字后跟对 a
Throwable
(通常是异常)的引用。
Example:
例子:
Throwable
: A class which you must extend in order to create your own, custom, throwable.
Throwable
:一个必须扩展的类才能创建自己的、自定义的、可抛出的。
Example:
例子:
回答by DixonD
Throw
is used for throwing exception, throws
(if I guessed correctly) is used to indicate that method can throw particular exception, and the Throwable
class is the superclass of all errors and exceptions in the Java
Throw
用于抛出异常,throws
(如果我猜对了)用于表示该方法可以抛出特定的异常,并且Throwable
该类是Java中所有错误和异常的超类
回答by Sachin Shanbhag
throw - It is used to throw an Exception.The throw statement requires a single argument : a throwable class object
throw - 用于抛出异常。 throw 语句需要一个参数:一个可抛出的类对象
throws - This is used to specifies that the method can throw exception
throws - 用于指定该方法可以抛出异常
Throwable - This is the superclass of all errors and exceptions in the Java language. you can throw only objects that derive from the Throwable class. throwable contains a snapshot of the execution stack of its thread at the time it was created
Throwable - 这是 Java 语言中所有错误和异常的超类。您只能抛出从 Throwable 类派生的对象。throwable 包含其线程在创建时的执行堆栈的快照
回答by oksayt
throw
: statement to throw objectt
wheret instanceof java.lang.Throwable
must be true.throws
: a method signature token to specify checked exceptionsthrow
n by that method.java.lang.Throwable
: the parent type of all objects that can be thrown (and caught).
throw
: 语句抛出对象t
wheret instanceof java.lang.Throwable
必须为真。throws
: 一个方法签名标记,用于指定throw
该方法所检查的异常n。java.lang.Throwable
:可以抛出(和捕获)的所有对象的父类型。
回答by Damian Leszczyński - Vash
This really easy to understand.
这真的很容易理解。
The java.lang.Throwable:
该java.lang.Throwable中:
The
Throwable
class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Javathrow
statement. Similarly, only this class or one of its subclasses can be the argument type in acatch
clause. More
该
Throwable
班是在Java语言中所有错误和异常的超类。只有作为此类(或其子类之一)的实例的对象才会被 Java 虚拟机抛出或可以被 Javathrow
语句抛出 。同样,只有此类或其子类之一可以是catch
子句中的参数类型 。 更多的
The key word throwsis used in method declaration, this specify what kind of exception[Throwable class] we may expect from this method.
关键字throws用于方法声明中,它指定我们可以从该方法中期望什么样的异常[Throwable class]。
The key word throwis used to throw an object that is instance of class Throwable.
关键字throw用于抛出一个对象,该对象是类 Throwable 的实例。
Lest see some example:
以免看一些例子:
We create ourself an exception class
我们为自己创建了一个异常类
public class MyException super Exception {
}
The we create a method that create a object from our exception class and throwsit using key word throw.
我们创建了一个方法,该方法从我们的异常类创建一个对象并使用关键字throw抛出它。
private void throwMeAException() throws MyException //We inform that this method throws an exception of MyException class
{
Exception e = new MyException (); //We create an exception
if(true) {
throw e; //We throw an exception
}
}
When we are going to use method throwMeAException()
, we are forced to take care of it in specific way because we have the information that it throws something, in this case we have three options.
当我们要使用 method 时throwMeAException()
,我们被迫以特定的方式处理它,因为我们有它抛出某些东西的信息,在这种情况下,我们有三个选项。
First option is using block try and catch to handle the exception:
第一个选项是使用块 try 和 catch 来处理异常:
private void catchException() {
try {
throwMeAException();
}
catch(MyException e) {
// Here we can serve only those exception that are instance of MyException
}
}
Second option is to pass the exception
第二种选择是传递异常
private void passException() throws MyException {
throwMeAException(); // we call the method but as we throws same exception we don't need try catch block.
}
Third options is to catch and re-throw the exception
第三个选项是捕获并重新抛出异常
private void catchException() throws Exception {
try {
throwMeAException();
}
catch(Exception e) {
throw e;
}
}
Resuming, when You need to stop some action you can throw the Exception that will go back till is not server by some try-catch block. Wherever You use method that throws an exception You should handle it by try-catch block or add the declarations to your methods.
恢复,当您需要停止某些操作时,您可以抛出异常,该异常将通过某个 try-catch 块返回直到不是服务器。无论您在何处使用引发异常的方法,您都应该通过 try-catch 块来处理它或将声明添加到您的方法中。
The exception of this rule are java.lang.RuntimeException
those don't have to be declared. This is another story as the aspect of exception usage.
这条规则的例外是java.lang.RuntimeException
那些不必声明的。这是另一个关于异常使用方面的故事。
回答by aizaz
Throw :
扔 :
is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.
用于实际抛出异常,而 throws 是方法的声明性。它们不可互换。
throw new MyException("Exception!);
Throws:
抛出:
This is to be used when you are not using the try catch statement in your code but you know that this particular class is capable of throwing so and so exception(only checked exceptions). In this you do not use try catch block but write using the throw clause at appropriate point in your code and the exception is thrown to the caller of the method and is handled by it. Also the throws keyword is used when the function may throw a checked exception.
当您没有在代码中使用 try catch 语句但您知道该特定类能够抛出某某异常(仅检查异常)时,将使用此方法。在这种情况下,您不使用 try catch 块,而是在代码中的适当位置使用 throw 子句编写,并将异常抛出给方法的调用者并由它处理。当函数可能抛出已检查的异常时,也会使用 throws 关键字。
public void myMethod(int param) throws MyException
回答by msysmilu
Same answer as above but with copy-paste pleasure:
与上述相同的答案,但具有复制粘贴的乐趣:
public class GsonBuilderHelper {
// THROWS: method throws the specified (checked) exception
public static Object registerAndRun(String json) throws Exception {
// registering of the NaturalDeserializer
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
Object natural = null;
try {
// calling the NaturalDeserializer
natural = gson.fromJson(json, Object.class);
} catch (Exception e) {
// json formatting exception mainly
Log.d("GsonBuilderHelper", "registerAndRun(json) error: " + e.toString());
throw new Exception(e); // <---- THROW: instance of class Throwable.
}
return natural;
}
}
回答by karto
There are 2 main types of Exceptions:
Runtime Exceptions(unchecked): eg. NullPointerException, ClassCastException,..
Checked Exceptions:eg. FileNotFoundException, CloneNotSupportedException, ..
异常有两种主要类型:
运行时异常(未检查):例如。NullPointerException、ClassCastException、..
检查异常:例如。FileNotFoundException, CloneNotSupportedException, ..
Runtime Exceptions are exceptions that occur at runtime and the developer should not try to catch it or stop it. You only write code to avoid them or issue a command throw, when the error criteria is met. We use throw inside the method body.
运行时异常是在运行时发生的异常,开发人员不应试图捕捉或阻止它。当满足错误标准时,您只需编写代码来避免它们或发出命令throw。我们在方法体中使用 throw。
public Rational(int num, int denom){
if(denom <= 0) {
throw new IllegalArgumentException("Denominator must be positive");
}
this.num=num;
this.denom=denom;
}
However for Checked Exceptions, the JVM expects you to handle it and will give compiler error if not handled so you declare that it throws that type of exception as seen below in the clone() method.
但是,对于检查异常,JVM 期望您处理它,如果未处理,则会给出编译器错误,因此您声明它会抛出该类型的异常,如下面的 clone() 方法所示。
Class Employee{
public Employee clone() throws CloneNotSupportedException{
Employee copy = (Employee)super.clone();
copy.hireDate = (Date)hireDate.clone();
return copy;
}
}