问题
Can any of you explain what the differences are between throw
, throws
and Throwable
and when to use which?
回答1:
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).
Example:
Throwable
: A class which you must extend in order to create your own, custom, throwable.
Example:
- Official exception-tutorial
回答2:
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).
See here for a tutorial on using exceptions.
回答3:
This really easy to understand.
The 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
The key word throws is used in method declaration, this specify what kind of exception[Throwable class] we may expect from this method.
The key word throw is used to throw an object that is instance of class 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 throws it using key word 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.
First option is using block try and catch to handle the exception:
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.
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.
回答4:
throw - It is used to throw an Exception.The throw statement requires a single argument : a throwable class object
throws - This is used to specifies that the method can throw exception
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
回答5:
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
How to Throw Exceptions
回答6:
Throw :
is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.
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.
public void myMethod(int param) throws MyException
回答7:
There are 2 main types of Exceptions:
Runtime Exceptions(unchecked): eg. NullPointerException, ClassCastException,..
Checked Exceptions: eg. 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.
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.
Class Employee{
public Employee clone() throws CloneNotSupportedException{
Employee copy = (Employee)super.clone();
copy.hireDate = (Date)hireDate.clone();
return copy;
}
}
回答8:
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;
}
}
来源:https://stackoverflow.com/questions/3940213/exception-handling-throw-throws-and-throwable