I am having trouble understanding how precise rethrow works in Java 7 and later versions. As pointed out in https://www.theserverside.com/tutorial/OCPJP-Use-more-precise-rethrow-in-exceptions-Objective-Java-7, in Java 7 and later versions we can use the throws clause, in a method declaration, with a comma-separated list of specific exceptions that the method could throw. If all these exceptions are subtypes of the general exception java.lang.Exception, we will be able to catch any of them in a catch block that catches this supertype, while letting client code (eg. a caller method) to know which of the possible subtypes exceptions actually occurred.
Initially, I thought that in order to let know client code which exception actually occurred, we needed to specify the list of specific exceptions in the throws clause. Nevertheless, in the following example the client code (the main() method) seems able to retrieve that information, even if we only specify the exception java.lang.Exception in the throws clause of the called method. Therefore, my question is:
Why the following code outputs the same, regardless of whether the throws clause of the method runException() is throws ExceptionA, ExceptionB or throws Exception ?
I am using Oracle JVM-12 in Eclipse. Thanks in advance!
class ExceptionA extends Exception{}
class ExceptionB extends Exception{}
public class RethrowingAndTypeChecking{
public static void runException(char what) throws Exception{
//public static void runException(char what) throws ExceptionA, ExceptionB{
try{
if(what == 'A')
throw new ExceptionA();
else if (what == 'B')
throw new ExceptionB();
}
catch(Exception e){
throw e;
}
}
public static void main (String args[]){
char ch;
for (int i=0;i<2;i++) {
if(i==0) ch='A';
else ch = 'B';
try{
runException(ch);
}
catch(ExceptionA e){
System.out.print("In main(), 'catch(ExceptionA e){}', caught exception: " + e.getClass());
}
catch(ExceptionB e){
System.out.print("In main(), 'catch(ExceptionB e){}', caught exception: " + e.getClass());
}
catch(Exception e){
System.out.print("In main(), 'catch(Exception e){}', caught exception: " + e.getClass());
}
System.out.println();
}
}
}
output:
In main(), 'catch(ExceptionA e){}', caught exception: class ExceptionA
In main(), 'catch(ExceptionB e){}', caught exception: class ExceptionB
What you're missing is the case where you need to handle those possible exceptions in different ways. Your code is catching individual exceptions, but it is, roughly speaking, performing the same action.
If you were to handle ExceptionA in a considerably different way from how you handle ExceptionB, then catching the broad Exception would not allow you to do that specifically:
catch(Exception e){
// something unexpected happened
// e could be an ExceptionA problem
// e could be an ExceptionB problem
// e could be any other unchecked exception
}
When the catch(Exception e){} block is entered, the exception could pretty much be anything, but you have only one generic code block to handle it.
Beside this, if the method you're calling declares specific checked exceptions, then the compiler can help you handle only those exceptions, thus adding to the predictability of the code
try{
runException(ch);
} catch(ExceptionA e){
// code specific to handling ExceptionA problems
} catch(ExceptionB e){
// code specific to handling ExceptionB problems
} catch(ExceptionC e){ //will not compile, because not declared by runException
// code specific to handling ExceptionB problems
}
Quoting #Carlos Heuberger, my code outputs the same, regardless of whether the throws clause of the method runException() is throws ExceptionA, ExceptionB or throws Exception because:
the run-time type of the exception is used to select the catch clause: see 14.20.1. Execution of try - catch
Whatever the exception reference type (in this case ExceptionA, ExceptionB or Exception) used to refer to the exception object thrown by method runException(), such method will throw objects of type either ExceptionA or ExceptionB. These objects will be assignment compatible with the catch parameters of the first two catch of the main() method.
After paragraphs 8.4.6, 11.2.3 and 14.20.1 of the Java Language Specification, I understood that what we actually specify in a throws clause of a method signature is the list of the exception reference types that will be assignment compatible with any possible exception object thrown from the method (given a class reference type we can make it point to instance objects of itself or to instance objects of its subclasses, not superclasses ). That tells any other caller method what exceptions it may have to deal with when invoking the method with the throws clause. In my code example, the advantage of using the clause throws ExceptionA, ExceptionB is that I will not need to catch java.lang.Exception in the main(). In fact, if I choose clause throws Exception in method runException() and delete the cath(Exception) block from the main() I will get a compile-time error. This is because even if we will be throwing ExceptionA or ExceptionB objects at run-time, the compiler will understand that method runException() may throw out an exception object of type Exception, which will not be assignment compatible with any of the catch parameters in the main() (Exception is a superclass of both ExceptionA and ExceptionB).
It's because, you've been throwing the Subclasses at,
try{
if(what == 'A')
throw new ExceptionA();
else if (what == 'B')
throw new ExceptionB();
}
of "Exception class" which are in turn being thrown out at,
catch(Exception e){
throw e;
}
after being assigned to "Exception class( at Exception e)", it will not make a difference if you specify throwing a Superclass type throws objectReference at
public static void runException(char what) throws Exception){
or Subclass type throws objectReferences at
public static void runException(char what) throws ExceptionA, ExceptionB){
As java compiler allows you to specify a throws ObjectReference, if it is of a Superclass of the object being thrown at the try statement.
These throws declarations are so that you list more explicitly what happens out of the method. Otherwise this is ordinary polymorphism: you use base class to combine in multiple subclasses, however you are definitely not changing the instances, this is why at runtime in both cases the exceptions are resolved to their concrete classes.
As a rule, you should never catch (Exception ex). Because this will catch RuntimeExceptions too. It sometimes makes sense to catch (Throwable t) or to use Thread.setDefaultUncaughtExceptionHandler to customize your uncaught exception handler to catch exceptions and then display them to the user. Sometimes I will catch an Exception, wrap it in a RuntimeException (or an Error) and throw that
When it comes to exceptions, you should really only be catching them when you can do something with them, or when you want to make sure that an exception doesn't cause the rest of the method to not process.
Personally I divide exceptions into 3 types
Problems in your code: This is something for you to fix
Problems with the user: For instance if you tell them to enter a number and they enter 'a', that's the user's error
"Friend" Exceptions: SocketException, for instance, is an example of this. If the socket closes and you have a thread waiting on input on it, it will throw this Exception, releasing the thread and letting you do clean-up on the socket.
Related
What is the point of catching and then also throwing an Exception like below? Is it bad practice to do both?
try{
//something
} catch (Exception e){
throw new RuntimeException("reason for exception");
}
Usually, such code is used to re-wrap exceptions, that means transforming the type of the exception. Typically, you do this when you are limited in what exceptions are allowed out of your method, but internally other types of exceptions can happen. For example:
class MyServiceImplementaiton implements MyService {
void myService() throws MyServiceException { // cannot change the throws clause here
try {
.... // Do something
} catch(IOException e) {
// re-wrap the received IOException as MyServiceException
throw new MyServiceException(e);
}
}
}
This idiom enables to keep propagating exceptions to the caller, while conforming to the throws clause in the interface and hide the details of the internals (the fact that IOExceptions can happen).
In practice, this is always better than just calling e.printStackTrace() which will actually "swallow" the error condition and let the rest of the program run as if nothing had happened. In this respect, behaviour of Eclipse is quite bad as it tends to auto-write such bad-practice constructs if the developer is not careful.
This is called rethrowing an exception, and it is a common pattern.
It allows you to change the class of the exception (such as in this case), or to add more information (also the case here, as long as that error string is meaningful).
It is often a good idea to attach the original exception:
throw new RuntimeException("cause of the problem", e);
Rethrowing as an unchecked exception (a RuntimeException) is sometimes necessary when you still want to throw an exception, but the API of your method does not allow a checked exception.
In your example, an Exception is caught and a RuntimeException is thrown, which effectively replaces a (potentially) checked exception with an unchecked exception that doesn't have to be handled by the caller, nor declared by the throwing method in a throws clause.
Some examples :
This code passes compilation :
public void SomeMethod ()
{
try {
//something
} catch (Exception e){
throw new RuntimeException("reason for exception");
}
}
This code doesn't pass compilation (assuming "something" may throw a checked exception) :
public void SomeMethod ()
{
//something
}
An alternative to catching the Exception and throwing an unchecked exception (i.e. RuntimeException) is to add a throws clause :
public void SomeMethod () throws Exception
{
//something
}
This is one use case of catching one type of exception and throwing another. Another use case is to catch one type of exception and throw another type of checked exception (that your method declares in its throws clause). It is sometimes done in order to group multiple exceptions that may be thrown inside a method, and only throw one type of exception to the caller of the method (which makes it easier for them to write the exception handling code, and makes sense if all those exceptions should be handled in the same manner).
Is it possible to create a user-defined exception and only catch it in a try-catch or does the user-defined exception have to be thrown with the throw statement.
Question: I am somewhat confused on whether when to use the throw keyword? I think that the throw is used with user-defined Exceptions.
Code: (Java)
public genericPanel() {
try {
if (i.length == size) {
throw new MyOwnDefinedError("Error - Size is 1 integer
to large");
}
for (int index=0;index<=i.length;index++) {
System.out.println(i[index]);
}
} catch (MyOwnDefinedError o) {
o.getMessage();
} catch (Exception e) {
e.getMessage();
}
}
class MyOwnDefinedError extends Exception {
MyOwnDefinedError(String myNewString) {
super( myNewString);
}
throw is used whenever you want to throw any Exception, whether user-defined or not. There is no difference between "pre-defined" exceptions (like IOException) or self-defined one, as in your MyOwnDefinedError.
You can read the answer in the java documentation on throwing excepions:
http://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Before you can catch an exception, some code somewhere must throw one.
Any code can throw an exception: your code, code from a package
written by someone else such as the packages that come with the Java
platform, or the Java runtime environment. Regardless of what throws
the exception, it's always thrown with the throw statement.
As you have probably noticed, the Java platform provides numerous
exception classes. All the classes are descendants of the Throwable
class, and all allow programs to differentiate among the various types
of exceptions that can occur during the execution of a program.
You can also create your own exception classes to represent problems
that can occur within the classes you write. In fact, if you are a
package developer, you might have to create your own set of exception
classes to allow users to differentiate an error that can occur in
your package from errors that occur in the Java platform or other
packages
Throw is used to throw an exception.
Throw is a part of method definition.
At a given point of time, a throw statement can only throw one exception.
A throw statement is post fixed by an instance of exception.
The throw keyword in java is used for user defined exceptions you are right. For example you are doing a banking application and you want to withdraw money from a customer's account. As is normal, the amount cannot go negative so you would throw a InvalidAmountException or something similar.
The keyword itself is used every time when an exceptional situation needs to be underlined, hence you will use throw for throwing any kind of exception, that exists in the API already or one that an user implemented.
As it goes for the handling of the exception - if one extends the Exception class from java, the Exception should be specifically placed on the method definition by using the throws keyword. If you want the exception to pop-up at runtime and maybe interrupt the execution of your program you can extend the RuntimeException. In this case, the exception handling it is optional - you don't have to specify it with throws or you don't have to wrap the execution of the method with try/catch block.
A complete tutorial on exception can be found here.
class Test
{
void testDivision(float a,float b)
{
if(b=0.0)
{
try
{
throw new MathematicalException("Please, do not divide by zero");
}
catch (MathematicalException ae)
{
System.out.println(ae);
}
}
else
{
float result=a/b;
System.out.println("Result:" + result);
}
}
public static void main(String args[])
{
float f1 = Float.parsefloat(args[0]);
float f2 = Float.parsefloat(args[1]);
Test t1 = new Test();
t1.testDivision(f1,f2);
}
class MathematicalException extends Exception
{
MathematicalException();
MathematicalException(String msg)
{
super(msg);
}
}
}
In Java, is it possible to make a method that has a throws statement to be not checked.
For example:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
You can try and do nothing about it:
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) { /* do nothing */ }
}
Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by #BaileyS.)
Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:
// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
throw new RuntimeException();
}
Classes that extend RuntimeException won't require a throws declaration as well.
And a word from Oracle about it:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
There are 3 things you can do :
Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.
Catch the exception and do nothing (not recommended) :
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) {
// Do nothing
}
}
Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :
public static void exceptionTest() throws Exception {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm no more forced to handle the exception
}
In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.
Exception is a checked exception, must caught or thrown.
NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.
From Exception documentation:
The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions. Checked exceptions need to be
declared in a method or constructor's throws clause if they can be
thrown by the execution of the method or constructor and propagate
outside the method or constructor boundary.
From the RuntimeException documentation:
RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or
constructor's throws clause if they can be thrown by the execution of
the method or constructor and propagate outside the method or
constructor boundary.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
Check this and this.
Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.
The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:
public void methodThatSecretlyThrowsAnException() {
Thread.currentThread().stop(new Exception());
}
or if your goal is to wrap an existing method that does declare its exception
public void methodThatSecretlyThrowsAnException() {
try {
methodThatAdmitsItThrowsAnException();
} catch(final Exception e) {
Thread.currentThread().stop(e);
}
}
(Needless to say, you should never do this.)
Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception
try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}
AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.
You can use a loophole in the Java Compiler. Add the following code:
public RuntimeException hideThrow(Throwable e) {
if (e == null)
throw new NullPointerException("e");
this.<RuntimeException>hideThrow0(e);
return null;
}
#SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
throw (GenericThrowable) e;
}
You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.
If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.
For example:
private class UnlikelyException extends RuntimeException {
public UnlikelyException (Exception e){
super (e);
}
}
Then wrap your code with a try-catch block and throw your exception, which you don't have to catch
try {
// Your code
} catch (Exception e) {
throw new UnlikelyException(e);
}
public void foo() {
begin();
try {
...
commit();
} catch (Exception e) {
rollback();
throw e;
}
}
In the sample above, there is an error because foo has no throws Exception. Adding that wouldn't make do the method's usability a lot of good either.
What's the best way to do this? How do you do something if an error occurs without really "handling" the error?
Since Java 8 we use
/**
* Cast a CheckedException as an unchecked one.
*
* #param throwable to cast
* #param <T> the type of the Throwable
* #return this method will never return a Throwable instance, it will just throw it.
* #throws T the throwable as an unchecked throwable
*/
#SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
You can rethrow a checked exception, but only by avoiding the compilers checked exception validation.
public void foo() throws MyCheckedException {
begin();
try {
...
commit();
} catch (Exception e) {
rollback();
// same as throwing an exception without the compiler knowing.
Thread.currentThread().stop(e);
}
}
Before you use stop() you should read http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html
Thread.currentThread().stop(e) .. is behaviorally identical to Java's throw operation, but circumvents the compiler's attempts to guarantee that the calling method has declared all of the checked exceptions that it may throw:
At least two approaches come to mind, which are usually going to be combined depending on what you want foo to do:
1. Catch and rethrow only the relevant exceptions
There are only so many exceptions the code in your main flow can throw (probably mostly SqlExceptions). So only catch and rethrow those, and declare that you're doing so. More to the point, rethrow only the ones you're not actually handling (in your simplified sample code, you're not handling any, but your real life code is probably more subtle).
Mind you, some of the exceptions may be runtime exceptions, and so you may want to combine this with the below.
2. Don't catch the exception at all
Like this:
// Signature changes to include any exceptions that really can be thrown
public void foo() throws XYZException, ABCException {
// A flag indicating that the commit succeeded
boolean done = false;
begin();
try {
// Don't have any `return` statements in here (or if you do,
// set `done` to `true` first)
...
commit();
done = true; // Commit didn't throw an exception, we're done
} finally {
// finally clause always happens regardless
if (!done) {
// We must be processing an exception; rollback
try {
rollback();
} catch (Exception e) {
// quash it (e.g., leave this block empty), we don't want
// to mask the real exception by throwing a different one
}
}
}
}
Naturally your signature needs to include any exceptions that may be thrown in the main flow, but that's what you're trying to do, if I'm understanding you correctly.
Again, you may well combine these two approaches, because you may want to handle some exceptions and not others.
Wrap it with some RuntimeException which is unchecked.
Adding that wouldn't make do the method's usability a lot of good either.
No. It will be good at documentation, also caller will take care handling it.
Also See
exception-thrown-inside-catch-block-will-it-be-caught-again
throws-or-try-catch
I'd say that in this case rolling back is handling the exception appropriately. It's one of the few cases where it's legitimate to catch and re-throw.
Simply catching and logging an exception is not what I would consider handling. Rather than rethrowing, in that case I'd rather see checked exceptions added to the method signature and let it bubble up.
you may throw a subclass of RuntimeException - they don't require a catch()
the key point is, why should you throw a new Exception from a catch block.
if you use catch then handle your exception there in your catch. If you have to inform the caller method with an exception, then don't catch the exception with try-catch, instead, sign your method with throws and let the caller catch the e xception.
or throw a RuntimeException, i find this idea less useful because of lack of readability, then you don't need to sign your method with throws.
Here you've chanced on one of the biggest religious schisms in the Java, ( if not wider ) , world. It boils down to those that feel, as TJ seems to, and I do too, that checked exceptions are valuable for many reasons, VS the Rod Johnson/Spring school that in the design of Java, checked exceptions were used in many instances where they shouldn't, say closing a resultset or socket, so because it was wrongly used in many cases, it makes them useless so all exceptions should be unchecked. There are many classes in the Spring framework that are very thin wrappers around standard Java objects, but convert checked exceptions to unchecked. It drives me berserk!
Anyway, put me down as strongly agreeing with everything TJ has said, but know that you'll probably never find a "right" answer.
It's worth mentioning some advances in this area.
First, in Java 7, it's possible to catch and throw generic exceptions, as long as what's declared inside the try block is caught or declared in the outer block. So this would compile:
void test() throws SQLException {
try {
conn.commit();
} catch (Throwable t) {
// do something
throw t;
}
}
This is well explained here : http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html
Another way is described here : http://blog.jooq.org/2012/09/14/throw-checked-exceptions-like-runtime-exceptions-in-java/
The reason you may want to use that has often to do with lambdas, or throwing exceptions from some generic methods. I ran into this when I wanted to replace repeating constructs of:
try {
do_operation
flag_success
} catch (Throwable e) {
flag_error
throw e;
}
With using a method of:
public static void wrapExec(RunnableT s) {
try {
s.run();
flag_success
} catch (Throwable t) {
flag_error
doThrow(t);
}
}
and therefore replacing the whole try/catch block with just
wrapExec(()->{do_operation})
Can any of you explain what the differences are between throw, throws and Throwable and when to use which?
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
throw: statement to throw object t where t instanceof java.lang.Throwable must be true.
throws: a method signature token to specify checked exceptions thrown 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.
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 Java
throw statement.
Similarly, only this class or one of
its subclasses can be the argument
type in a catch 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.
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
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
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
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;
}
}
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;
}
}