When an Exception
is generated, there are two ways to deal with it.
- Handle the Exception - this uses
catch
block
- Declare the Exception - this uses
throws
block
So, dealing with an already generated exception is done by catch
or throws
.
On the other hand, throw
is used while an Exception is "generated".
Typically, the throw
keyword is used when you're instantiating an Exception object or while cascading an already generated exception to the caller.
For example,
public void doSomething(String name) throws SomeException { // Exception declared
if( name == null ){ // cause of the exception
throw new SomeException(); // actual NEW exception object instantiated and thrown
}
// Do something here
.
.
.
}
In the calling method,
public static void main(String[] args) throws SomeException{ // Need to declare exception because you're "throwing" it from inside this method.
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
throw e;// throw the exception object generated in doSomething()
}
}
Alternately, you can "handle" the exception in the catch block:
public static void main(String[] args) { // No need to declare exception
try { // try doing some thing that may possibly fail
doSomething(name);
} catch (SomeException e){
System.out.println("Exception occurred " + e.getMessage()); // Handle the exception by notifying the user.
}
}
Hope this helps.
Addendum - Exception Handling glossary
try
- used for invoking code that can potentially cause exceptions or with resources such as Files/Streams/Network/Database connections.
catch
- used immediately after a try
block to "handle" or "throw" exceptions. Optional if finally
is used.
finally
- used immediately after a try
or catch
block. Optional. Used for executing code that "must" be executed. Code within a finally
block always gets executed - even if the try
or catch
has a return
statement.
throw
- used to "push" or "cascade" exceptions through the calling methods. Always used inside a method.
throws
- used to "declare" that a method will be throwing an exception if something goes wrong. Always used as part of method signature.
Addional Reading
Here's an elaborate article to help you understand the try-catch-finally semantics in java.
Update
To answer your other question,
Why don't we require to use catch , finally block for throws
IOException ?
Think of catch
and throws
as mutually exclusive constructs. (This is not always true, but for your understanding, it's good to start with this thought.)
You declare a method that it throws IOException
. This piece of code is written at a point where you declare the method. And, syntactically, you cannot place a method declaration inside a try block.
How does throws is handle the exception. ?
Like I mentioned before, catch
and finally
are used during exception handling. throws
is just used to cascade the exception back to the caller.